开发者

unwrap T from Nullable<T>

Wanted a simple but efficient method to get value from Nullable when T is not known开发者_运维技巧 at the compile time.

So far have something like this:

public static object UnwrapNullable(object o)
{
    if (o == null)
        return null;

    if (o.GetType().IsGenericType && o.GetType().GetGenericTypeDefinition() == typeof(Nullable<>))
        return ???

    return o;
}

anything can be done here without dipping into dynamic code generation?

used on .NET 2.0


o can never refer to an instance of Nullable<T>. If you box a nullable value type value, you either end up with a boxed value of the non-nullable underlying type, or a null reference.

In other words, o.GetType() can never return Nullable<T> for any value of o - regardless of the type of o. For example:

Nullable<int> x = 10;
Console.WriteLine(x.GetType()); // System.Int32

Here we end up boxing the value of x because GetType() is declared on object and not overridden in Nullable<T> (because it's non-virtual). It's a little bit of an oddity.


It does not makes sense.

If you have code:

int? x = null; //int? == Nullable<int>
if ( null == x ) { Console.WriteLine("x is null"); }
else { Console.WriteLine( "x is " + x.ToString() ); }

The result will be "x is null" printed in console.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜