如何通过反射获得可空类型的值

alf*_*dev 12 c# reflection

使用反射我需要检索a的属性值 Nullable Type of DateTime

我怎样才能做到这一点?

当我尝试propertyInfo.GetValue(object, null)它不起作用.

谢谢

我的代码:

 var propertyInfos = myClass.GetType().GetProperties();

 foreach (PropertyInfo propertyInfo in propertyInfos)
 {
     object propertyValue= propertyInfo.GetValue(myClass, null);
 }
Run Code Online (Sandbox Code Playgroud)

propertyValue结果对于可空类型始终为null

Mar*_*ell 29

反思并且Nullable<T>有点痛苦; 反射使用object,并Nullable<T>具有特殊的装箱/拆箱规则object.因此,当你拥有object它时,它 不再Nullable<T>- 它null或者是价值本身.

int? a = 123, b = null;
object c = a; // 123 as a boxed int
object d = b; // null
Run Code Online (Sandbox Code Playgroud)

这有时让它有点混乱,注意到你无法TNullable<T>装箱的空白中获取原件,因为你所拥有的只是一个null.

  • 如果使用 `Nullable.GetUnderlyingType(type)` 不为 null,则可以获取盒装 nullable 的基础类型 (2认同)