码迷,mamicode.com
首页 > 其他好文 > 详细

由Nullable模式想到的ToString的扩展

时间:2014-08-05 15:26:49      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   ar   代码   div   

 

虽然关于null的一切争论永不停息,但根据实际开发经历,很多时候需要判断无聊的null,并且有些的判断是可有可无的,尤其是在表现层。

 string e = null;

 if (e != null)
 {
     Console.WriteLine(e.ToString());
 }

上述代码如果能换成这样是不是更好:

  e = null;
  Console.WriteLine(e.ToString(false));//不要报异常

利用.net自带的缺省参数(.net4)和扩展方法等特性,下面是完整代码:

    class Program
    {
        static void Main(string[] args)
        {
            string e = null;

            if (e != null)
            {
                Console.WriteLine(e.ToString());
            }

            e = null;
            Console.WriteLine(e.ToString(false));//不要报异常
            Console.WriteLine(e.ToString(true));//要求异常
            Console.WriteLine(e.ToString());//默认报异常
            Console.WriteLine("OK");
            Console.Read();
        }
    }

    public static class s
    {
        public static string ToString(this string s, bool checkNull = true)
        {
            if (checkNull && s == null) { throw new NullReferenceException(); }
            return s + 123;
        }
    }


 

由Nullable模式想到的ToString的扩展,布布扣,bubuko.com

由Nullable模式想到的ToString的扩展

标签:style   blog   color   os   io   ar   代码   div   

原文地址:http://www.cnblogs.com/langu/p/3892275.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!