如何通过反射代码(c#)设置可空类型?

dot*_*der 21 c# reflection

我需要使用反射设置类的属性.

我有一个Dictionary<string,string>属性名称和字符串值.

在反射循环中,我需要在为每个属性设置值时将字符串值转换为适当的属性类型.其中一些属性类型是可空类型.

  1. 如果属性是可以为空的类型,我如何从PropertyInfo中知道?
  2. 如何使用反射设置可空类型?

编辑: 此博客评论中定义的第一个方法似乎也可以解决这个问题:http: //weblogs.asp.net/pjohnson/archive/2006/02/07/437631.aspx

Ken*_*art 14

  1. 一种方法是:

    type.GetGenericTypeDefinition() == typeof(Nullable<>)
    
    Run Code Online (Sandbox Code Playgroud)
  2. 只需设置为任何其他反射代码:

    propertyInfo.SetValue(yourObject, yourValue);
    
    Run Code Online (Sandbox Code Playgroud)

  • 对于非泛型类型,您的"1"将中断; "Nullable.GetUnderlyingType(type)!= null"更安全. (6认同)

Mar*_*ell 14

为什么你需要知道它是否可以为空?你的意思是"引用型"或" Nullable<T>"?

无论哪种方式,使用字符串值,最简单的选项将是通过TypeConverter,更容易(并且更准确)可用于PropertyDescriptor:

PropertyDescriptorCollection props = TypeDescriptor.GetProperties(obj);
// then per property...
PropertyDescriptor prop = props[propName];
prop.SetValue(obj, prop.Converter.ConvertFromInvariantString(value));
Run Code Online (Sandbox Code Playgroud)

这应该使用正确的转换器,即使设置per-property(而不是per-type).最后,如果你正在做很多这样的事情,这允许加速HyperDescriptor,而不改变代码(除了为类型启用它,只做一次).


Joe*_*oel 7

特别是将整数转换为枚举并分配给可以为空的枚举属性:

int value = 4;
if(propertyInfo.PropertyType.IsGenericType
&& Nullable.GetUnderlyingType(propertyInfo.PropertyType) != null
&& Nullable.GetUnderlyingType(propertyInfo.PropertyType).IsEnum)
{
    var enumType = Nullable.GetUnderlyingType(propertyInfo.PropertyType);
    var enumValue = Enum.ToObject(enumType, value);
    propertyInfo.SetValue(item, enumValue, null);

    //-- suggest by valamas
    //propertyInfo.SetValue(item, (value == null ? null : enumValue), null);
}
Run Code Online (Sandbox Code Playgroud)