如果我有类似的东西:
object value = null;
Foo foo = new Foo();
PropertyInfo property = Foo.GetProperties().Single(p => p.Name == "IntProperty");
property.SetValue(foo, value, null);
Then foo.IntProperty
被设置为0
, 虽然value = null
。看起来它正在做类似的事情IntProperty = default(typeof(int))
。我想扔一个InvalidCastException
if IntProperty
不是“可为空”类型(Nullable<>
或参考)。我正在使用反射,所以我提前不知道类型。我该怎么做呢?
如果您有PropertyInfo
,您可以检查.PropertyType
; if .IsValueType
是真的,并且如果Nullable.GetUnderlyingType(property.PropertyType)
为 null,则它是不可为 null 的值类型:
if (value == null && property.PropertyType.IsValueType &&
Nullable.GetUnderlyingType(property.PropertyType) == null)
{
throw new InvalidCastException ();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)