简体   繁体   中英

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.

double? 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();
}  

你有每个Nullable类型的GetValueOrDefault方法,这还不够吗?

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();
} 

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 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM