如何检查可空类型是否具有MemberInfo中的值

时间:2011-08-29 14:05:13

标签: c# reflection

如果我有MemberInfo可空类型,我如何确定它是否已分配值?

2 个答案:

答案 0 :(得分:2)

MemberInfo没有获取值的方法,因为MemberInfo可以引用方法,属性或字段。其中每个都有自己的类型,继承自MemberInfo,分别是MethodInfoPropertyInfoFieldInfo。这些类型中的每一种都有自己从目标实例获取值的方法(我将使用一个名为instance的变量来引用相关实例):

TL;下面的DR版本:要检查值是否为null,只需执行以下操作:

if (value == null)
{
    ...
}

通过调用上面的相应方法获得值后,可以使用该值进行比较。装箱Nullable<T>时,适用特殊规则;当Nullable<T>的“空”值被加框时,则返回实际的空引用。当盒装非空Nullable<T>时,底层值就是盒装(换句话说,Nullable<T>的实例永远不会被装箱到堆上)。这个例子可以让它更清晰:

int? foo = 10;
int? bar = null;
int baz = 10;

object value;

value = foo; // The integer 10 is boxed and placed on the heap
value = bar; // Nothing is boxed and value is set to null
value = baz; // The integer 10 is boxed and placed on the heap

由于这些特殊规则,您可以将它与null进行比较以查看它是否为空值,您可以直接转换为基本类型(如果它是null或不是该类型,将导致运行时异常),或者你可以将一个条件强制转换回可以为空的类型,这将返回你的可空值。:

if (value == null)
{
    ...
}

int val = (int)value;

int? val = value as int?;

答案 1 :(得分:1)

假设您的MemberInfoPropertyInfo

PropertyInfo prop = ...
object value = prop.GetValue(instance, null);
if (value != null)
{
    ...
}