开发者

Detect nullable type

Is it possible to detect a Nullable type (cast into an object) when it is null?

Since Nullable<T> is really a struct I think it should be possible.

dou开发者_StackOverflow中文版ble? d = null;
var s = GetValue(d); //I want this to return "0" rather than ""

public string GetValue(object o)
{
    if(o is double? && !((double?)o).HasValue) //Not working with null
       return "0";
    if(o == null)
       return "";
    return o.ToString();
}  


http://msdn.microsoft.com/en-us/library/ms228597(v=vs.80).aspx

Objects based on nullable types are only boxed if the object is non-null. If HasValue is false, then, instead of boxing, the object reference is simply assigned to null.

and

If the object is non-null -- if HasValue is true -- then boxing takes place, but only the underlying type that the nullable object is based upon is boxed.

So you either have a double or a null.

public string GetValue(object o)
{
    if(o == null) // will catch double? set to null
       return "";

    if(o is double) // will catch double? with a value
       return "0";

    return o.ToString();
} 


You have the method GetValueOrDefault for every Nullable type, isn't it enough ?


Your method currently takes object, which means the nullable value will be boxed... and will no longer be a nullable value. The value of o will either be a boxed value of the non-nullable type, or a null reference.

If at all possible, change your method to be generic:

public string GetValue<T>(T value)
{
    // Within here, value will still be a Nullable<X> for whatever type X
    // is appropriate. You can check this with Nullable.GetUnderlyingType
}


If o is null then o is double? will be false. No matter the value of your input parameter double? d


From what I understand, if you are trying to detect if ANY object is nullable, this can be written fairly easily.

try this...

public static bool IsNullable(dynamic value)
{
    try
    {
        value = null;
    }
    catch(Exception)
    {
        return false;
    }
    return true;
}

Simple!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜