由Nullable模式想到的ToString的扩展

 

虽然关于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;
        }
    }


 

posted @ 2014-08-05 14:52  Tony二师弟  阅读(288)  评论(0编辑  收藏  举报