• 由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;
            }
        }


     

  • 相关阅读:
    【PHPStorm使用手册】如何设置字体大小?
    Django——admin组件简单入门
    cookie与session
    Django
    练习题
    线程理论之大白话
    队列
    初识gevent模块
    Python第三方模块安装
    Python标准模块_concurrent.futures
  • 原文地址:https://www.cnblogs.com/langu/p/3892275.html
Copyright © 2020-2023  润新知