【发布时间】:2013-04-29 04:39:19
【问题描述】:
我对@987654321@类型的以下行为感到困惑:
class TestClass {
public int? value = 0;
}
TestClass test = new TestClass();
现在,Nullable.GetUnderlyingType(test.value) 返回底层的Nullable 类型,即int。
但是,如果我尝试获取这样的字段类型
FieldInfo field = typeof(TestClass).GetFields(BindingFlags.Instance | BindingFlags.Public)[0];
然后我调用
Nullable.GetUnderlyingType(field.FieldType).ToString()
它返回一个System.Nullable[System.Int32] 类型。这意味着Nullable.GetUnderlyingType() 方法具有不同的行为,具体取决于您获取成员类型的方式。为什么呢?如果我只是使用test.value,我怎么知道它是Nullable而不使用反射?
【问题讨论】:
-
是
typeof(field.FieldType) == typeof(test.value)?我可以想象,由于该方法称为GetUnderlyingType,因此它对类型和类型的实例的作用不同。 -
不,
typeof(field.FieldType)返回Nullable<int>,而typeof(test.value)只是返回System.Int32——我在问,为什么它们返回不同的类型?此外,如何检查test.value是否为Nullable? -
你试过
test.value is Nullable<int>吗?尝试int以确保它不会给出误报。 IMO 的奇怪行为来自typeof(test.value)返回System.Int32而不是Nullable<int>的奇怪事实。 -
test.value根据定义总是返回一个int。 -
什么意思?
test.value is Nullable<int>是一个检查,它返回一个bool,指示test.value是否是Nullable<int>的一个实例。
标签: c# reflection nullable