本文介绍了PropertyInfo SetValue和null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有类似的东西

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))的操作。如果 IntProperty 不是可空的类型( Nullable< InvalidCastException ;> 或参考)。我正在使用反射,所以我不知道提前使用的类型。我该怎么做?

Then foo.IntProperty gets set to 0, even though value = null. It appears it's doing something like IntProperty = default(typeof(int)). I would like to throw an InvalidCastException if IntProperty is not a "nullable" type (Nullable<> or reference). I'm using Reflection, so I don't know the type ahead of time. How would I go about doing this?

推荐答案

如果您有 PropertyInfo ,您可以检查 .PropertyType ;如果 .IsValueType 为true,并且如果 Nullable.GetUnderlyingType(property.PropertyType)为null,则为非-可空的值类型:

If you have the PropertyInfo, you can check the .PropertyType; if .IsValueType is true, and if Nullable.GetUnderlyingType(property.PropertyType) is null, then it is a non-nullable value-type:

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

这篇关于PropertyInfo SetValue和null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 02:19