c# – 检测可空类型

当它为空时,是否可以检测到Nullable类型(强制转换为对象)?

由于Nullable< T>我认为这应该是可能的结构.

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

解决方法:

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.

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.

所以你有一个double或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();
} 
上一篇:c# – DateTimeOffset?(Nullable)和DateTimeOffset.Now之间的区别


下一篇:c# – 可空值的类型只是常规值类型的包装吗?