PropertyInfo SetValue和nulls

Nel*_*mel 10 c# reflection default

如果我有类似的东西:

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

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

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

Mar*_*ell 12

如果你有PropertyInfo,你可以检查.PropertyType; 如果.IsValueType为true,如果Nullable.GetUnderlyingType(property.PropertyType)为null,则它是一个不可为空的值类型:

        if (value == null && property.PropertyType.IsValueType &&
            Nullable.GetUnderlyingType(property.PropertyType) == null)
        {
            throw new InvalidCastException ();
        }
Run Code Online (Sandbox Code Playgroud)