简体   繁体   English

检测可空类型

[英]Detect nullable type

Is it possible to detect a Nullable type (cast into an object) when it is null? 当它为空时,是否可以检测到Nullable类型(强制转换为对象)?

Since Nullable<T> is really a struct I think it should be possible. 由于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();
}  

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

http://msdn.microsoft.com/en-us/library/ms228597(v=vs.80).aspx 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. 如果对象为非null,则仅基于可空类型的对象进行装箱。 If HasValue is false, then, instead of boxing, the object reference is simply assigned to null. 如果HasValue为false,则将对象引用简单地指定为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. 如果对象是非null - 如果HasValue为true - 则进行装箱,但只有可以为空的对象所基于的基础类型被装箱。

So you either have a double or a null . 所以你有一个doublenull

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. 您的方法当前采用object ,这意味着可以为空的值加框...并且将不再是可以为空的值。 The value of o will either be a boxed value of the non-nullable type, or a null reference. 的值o 要么是所述非空类型的装箱值,或空引用。

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? 如果onullo is double? will be false. 将是假的。 No matter the value of your input parameter double? d 无论输入参数的值是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! 简单!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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