- ConsoleCommandLine.zip
- ConsoleCommandLine
- CommandLineParser
- CommandLineTests
- ConsoleCommandLine.sln
- ConsoleCommandLine.sln.docstates.suo
- ConsoleCommandLine.suo
- ConsoleCommandLine.vsmdi
- ConsoleCommandLine
- Local.testsettings
- TraceAndTestImpact.testsettings
|
namespace CommandLineParser
{
using System;
/// <summary>
/// Class for converting arguments to objects
/// </summary>
public class ObjectSerialiser
{
/// <summary>
/// Sets the value for the appropriate property in the Argument Definition.
/// </summary>
/// <param name="map">The argument map.</param>
/// <param name="argument">The argument.</param>
/// <param name="arguments">The argument definition.</param>
public static void SetValue(ArgumentMap map, Argument argument, IArgumentDefinition arguments)
{
var property = map.Property;
Type t = property.PropertyType;
property.SetValue(arguments, ConvertFromString(argument.Value, t), null);
}
/// <summary>
/// Converts an object from a string.
/// </summary>
/// <param name="s">The value string to convert.</param>
/// <param name="t">The type of the expected object.</param>
/// <returns>The converted object</returns>
public static object ConvertFromString(string s, Type t)
{
if (t.IsEnum)
{
return Enum.Parse(t, s);
}
// boolean accepts argument values of true, True, false, False, 1, 0
if (t == typeof(bool))
{
// If type is bool with null or empty value return true
if (string.IsNullOrWhiteSpace(s))
{
return true;
}
bool b;
if (bool.TryParse(s, out b))
{
return b;
}
int i = Convert.ToInt32(s);
if (i < 0 || i > 1)
{
throw new FormatException("Invalid boolean type. Must be 0 or 1.");
}
return Convert.ToBoolean(i);
}
return Convert.ChangeType(s, t);
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.