24

替代标题:在运行时动态转换为类型。

我想将 Object 转换为将在运行时分配的类型。

例如,假设我有一个将字符串值(来自 a TextBox or Dropdownlist)分配给 a 的函数Object.Property

如何将值转换为正确的类型?例如,它可以是整数、字符串或枚举。

Public void Foo(object obj,string propertyName,object value)
{
  //Getting type of the property og object.
  Type t= obj.GetType().GetProperty(propName).PropertyType;

  //Now Setting the property to the value .
  //But it raise an error,because sometimes type is int and value is "2"
  //or type is enum (e.a: Gender.Male) and value is "Male"
  //Suppose that always the cast is valid("2" can be converted to int 2)

  obj.GetType().GetProperty(propName).SetValue(obj, value, null);
}
4

5 回答 5

44

您需要使用 Convert.ChangeType(...) 函数 [注意:在下面的函数中,输入 propertyValue 可以很容易地成为 object 类型......我只是预先准备了一个字符串版本]:

/// <summary>
/// Sets a value in an object, used to hide all the logic that goes into
///     handling this sort of thing, so that is works elegantly in a single line.
/// </summary>
/// <param name="target"></param>
/// <param name="propertyName"></param>
/// <param name="propertyValue"></param>
public static void SetPropertyValueFromString(this object target,               
                              string propertyName, string propertyValue)
{
    PropertyInfo oProp = target.GetType().GetProperty(propertyName);
    Type tProp = oProp.PropertyType;

    //Nullable properties have to be treated differently, since we 
    //  use their underlying property to set the value in the object
    if (tProp.IsGenericType
        && tProp.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
    {
        //if it's null, just set the value from the reserved word null, and return
        if (propertyValue == null)
        {
            oProp.SetValue(target, null, null);
            return;
        }

        //Get the underlying type property instead of the nullable generic
        tProp = new NullableConverter(oProp.PropertyType).UnderlyingType;
    }

    //use the converter to get the correct value
    oProp.SetValue(target, Convert.ChangeType(propertyValue, tProp), null);
}
于 2011-09-30T21:21:07.003 回答
2

通用类型转换器就是您所寻求的!?绝非易事。。

试试这个方法:

通用型转换器

你可以在 NuGetInstall-Package UniversalTypeConverter

另外,在这里使用是Generics不可能的吗?如果您至少知道转换的目标类型,它将有助于解决方案。

于 2011-09-30T21:20:09.997 回答
1

这是另一种方法,但我不确定

不支持泛型类型:

public void Foo(object obj,string propertyName,object value) 
{ 
    //Getting type of the property og object. 
    Type type = obj.GetType().GetProperty(propertyName).PropertyType;

    obj.GetType().GetProperty(propertyName).SetValue(obj, Activator.CreateInstance(type, value), null);
} 

支持泛型类型:

public void Foo(object obj,string propertyName,object value) 
{ 
    //Getting type of the property og object. 
    Type type = obj.GetType().GetProperty(propertyName).PropertyType;

    if (type.IsGenericType)
        type = type.GetGenericArguments()[0];

    obj.GetType().GetProperty(propertyName).SetValue(obj, Activator.CreateInstance(type, value), null);
} 
于 2011-09-30T21:57:52.693 回答
0

我不确定它是否有效,但试一试:

public static T To<T>(this IConvertible obj)
{
  return (T)Convert.ChangeType(obj, typeof(T));
}

Public void Foo(object obj,string propertyName,object value)
{
    Type t= obj.GetType().GetProperty(propName).PropertyType;
    obj.GetType().GetProperty(propName).SetValue(obj, value.To<t>(), null);
}
于 2011-09-30T21:23:27.880 回答
0

我在 C# 中使用了转换函数。我进行转换的方式是使用反射。:

Type type = this.myObject.GetType();

if (type.Name == "MyObjectClass") {
var Voucherrequest = (MyObjectClass)Convert.ChangeType(myObject, typeof(MyObjectClass));

这一切都假设您知道要转换为哪种类型。您甚至可以进行切换并拥有多种您想要反映的类型。

于 2016-07-21T17:27:44.847 回答