PropertyInfo SetValue和nulls

时间:2010-06-15 22:19:17

标签: c# reflection default

如果我有类似的话:

object value = null;
Foo foo = new Foo();

PropertyInfo property = Foo.GetProperties().Single(p => p.Name == "IntProperty");
property.SetValue(foo, value, null);

然后foo.IntProperty设置为0,即使value = null。看起来它正在做IntProperty = default(typeof(int))之类的事情。如果InvalidCastException不是“可空”类型(IntProperty或引用),我想抛出Nullable<>。我正在使用Reflection,所以我不提前知道类型。我该怎么做呢?

2 个答案:

答案 0 :(得分:12)

如果您拥有PropertyInfo,则可以查看.PropertyType;如果.IsValueType为真,并且Nullable.GetUnderlyingType(property.PropertyType)为空,那么它是一个不可为空的值类型:

        if (value == null && property.PropertyType.IsValueType &&
            Nullable.GetUnderlyingType(property.PropertyType) == null)
        {
            throw new InvalidCastException ();
        }

答案 1 :(得分:1)

您可以使用PropertyInfo.PropertyType.IsAssignableFrom(value.GetType())表达式来确定是否可以将指定值写入属性。但是当value为null时你需要处理大小写,所以在这种情况下,只有当属性类型为可空或属性类型为引用类型时,才能将它分配给属性:

public bool CanAssignValueToProperty(PropertyInfo propertyInfo, object value)
{
    if (value == null)
        return Nullable.GetUnderlyingType(propertyInfo.PropertyType) != null ||
               !propertyInfo.IsValueType;
    else
        return propertyInfo.PropertyType.IsAssignableFrom(value.GetType());
}

此外,您可能会发现有用的Convert.ChangeType方法将可转换值写入属性。