如何通过反射获取 Nullable 类型的值
使用反射,我需要检索 可为 Null 类型的 DateTime
的属性值,
我该如何执行此操作?
当我尝试 propertyInfo.GetValue(object, null)
它不起作用。
谢谢
我的代码:
var propertyInfos = myClass.GetType().GetProperties();
foreach (PropertyInfo propertyInfo in propertyInfos)
{
object propertyValue= propertyInfo.GetValue(myClass, null);
}
对于可为 null 的类型,propertyValue 结果始终为 null
Using reflection I need to retrieve the value of a propery of a Nullable Type of DateTime
How can I do this?
When I try propertyInfo.GetValue(object, null)
it does not function.
thx
My code:
var propertyInfos = myClass.GetType().GetProperties();
foreach (PropertyInfo propertyInfo in propertyInfos)
{
object propertyValue= propertyInfo.GetValue(myClass, null);
}
propertyValue result always null for nullable type
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
反射和
Nullable
有点麻烦;反射使用object
,并且Nullable
对object
有特殊的装箱/拆箱规则。因此,当您拥有一个对象
时,它不再是一个Nullable
- 它要么是null
或值本身。即,
这有时会让人有点困惑,并且请注意,您无法从具有已被装箱,因为您所拥有的只是
null
。Reflection and
Nullable<T>
are a bit of a pain; reflection usesobject
, andNullable<T>
has special boxing/unboxing rules forobject
. So by the time you have anobject
it is no longer aNullable<T>
- it is eithernull
or the value itself.i.e.
This makes it a bit confusing sometimes, and note that you can't get the original
T
from an emptyNullable<T>
that has been boxed, as all you have is anull
.给定简单的类:
并且代码:
value 具有 null (如果 .Bar 为 null)或 DateTime 值。这其中的哪一部分不适合您?
Given simple class:
And the code:
value has either null (if .Bar is null) or the DateTime value. What part of this isn't working for you?