加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 检测可空类型

发布时间:2020-12-16 00:00:20 所属栏目:百科 来源:网络整理
导读:当它为空时,是否可以检测到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)
当它为空时,是否可以检测到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();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读