c# - 在 C#.NET 中动态转换为类型

标签 c# reflection casting getproperty

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

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

例如,假设我有一个将字符串值(从 TextBox 或 Dropdownlist)分配给 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);
}

最佳答案

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

/// <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);
}

关于c# - 在 C#.NET 中动态转换为类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7616177/

相关文章:

C++ - 允许通过基类(接口(interface))访问,禁止通过派生类(具体实现)访问?

C#:Server.Mappath 如何读取文件?

c# - 在 C# 中从 XML Writer 创建 XML 元素对象

python - 如何测试一个类是否包含特定属性?

java - 如何解决先有鸡还是先有蛋的问题?

c# - 在 C# 中确定对象的值

c# - 在c#中获取从base64和UTF8转换后的视频文件

c# - 使用 float 时,ASP.NET MVC ViewModel 绑定(bind)十进制为空

generics - 如何在 Kotlin 中获取具体泛型参数的实际类型参数?

java - Java 中的动态转换