如何判断可空类型和值得转换!

代码如下:

    public ActionResult Index(int? Key)
        {
            //要把KeyValue 转成KeyValue;
            string KeyValue;
    
            return View();
        }

方案一:

    public ActionResult Index(int? Key)
        {
            //要把KeyValue 转成KeyValue;
            string KeyValue;
            KeyValue = (Key ?? 0) == 0 ? string.Empty : Key.Value.ToString();
            return View();
        }

方案二:

    public ActionResult Index(int? Key)
        {
            //要把KeyValue 转成KeyValue;
            string KeyValue;
            Func<string> v = delegate()
            {
                if (Key == null)
                {
                    return string.Empty;
                }
                return Key.Value.ToString();
            };
            KeyValue = v();
            return View();
        }

方案三:

    public ActionResult Index(int? Key)
        {
            //要把KeyValue 转成KeyValue;
            string KeyValue;
            Func<string> v = delegate()
            {
                if (Key.HasValue==false)
                {
                    return string.Empty;
                }
                return Key.Value.ToString();
            };
            KeyValue = v();
            return View();
        }

其实方案三和方案二是一样的 只是一个判断null 一个用自带的方法返回true 或false

其实还有更多的方法 希望路过的大神,提供更好的方法

原文地址:https://www.cnblogs.com/flyfish2012/p/2880121.html