ChangeType() public static method

public static ChangeType ( object value, Type type ) : object
value object
type System.Type
return object
Exemplo n.º 1
0
        internal static void AssignValue(object command, PropertyInfo property, string option, object value)
        {
            try
            {
                if (TypeHelper.IsMultiValuedProperty(property))
                {
                    // If we were able to look up a parent of type ICollection<>, perform a Add operation on it.
                    // Note that we expect the value is a string.
                    var stringValue = value as string;
                    Debug.Assert(stringValue != null);

                    dynamic list = property.GetValue(command, null);
                    // The parameter value is one or more semi-colon separated items that might support values also
                    // Example of a list value : nuget pack -option "foo;bar;baz"
                    // Example of a keyvalue value: nuget pack -option "foo=bar;baz=false"
                    foreach (var item in stringValue.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        if (TypeHelper.IsKeyValueProperty(property))
                        {
                            int eqIndex = item.IndexOf("=", StringComparison.OrdinalIgnoreCase);
                            if (eqIndex > -1)
                            {
                                string propertyKey   = item.Substring(0, eqIndex);
                                string propertyValue = item.Substring(eqIndex + 1);
                                list.Add(propertyKey, propertyValue);
                            }
                        }
                        else
                        {
                            list.Add(item);
                        }
                    }
                }
                else if (TypeHelper.IsEnumProperty(property))
                {
                    var enumValue = Enum.GetValues(property.PropertyType).Cast <object>();
                    value = GetPartialOptionMatch(enumValue, e => e.ToString(), e => e.ToString(), option, value.ToString());
                    property.SetValue(command, value, index: null);
                }
                else
                {
                    property.SetValue(command, TypeHelper.ChangeType(value, property.PropertyType), index: null);
                }
            }
            catch (CommandLineException)
            {
                throw;
            }
            catch
            {
                throw new CommandLineException(TaskResources.InvalidOptionValueError, option, value);
            }
        }