开发者

How to get value of a Nullable Type via reflection

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.GetValu开发者_高级运维e(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


Reflection and Nullable<T> are a bit of a pain; reflection uses object, and Nullable<T> has special boxing/unboxing rules for object. So by the time you have an object it is no longer a Nullable<T> - it is either null or the value itself.

i.e.

int? a = 123, b = null;
object c = a; // 123 as a boxed int
object d = b; // null

This makes it a bit confusing sometimes, and note that you can't get the original T from an empty Nullable<T> that has been boxed, as all you have is a null.


Given simple class:

public class Foo
{
    public DateTime? Bar { get; set; }
}

And the code:

Foo foo = new Foo();

foo.Bar = DateTime.Now;

PropertyInfo pi = foo.GetType().GetProperty("Bar");

object value = pi.GetValue(foo, null);

value has either null (if .Bar is null) or the DateTime value. What part of this isn't working for you?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜