大家可能经常遇到这种情况:当一个对象为null时,调用这个对象的方法或者属性时,就会报错:“Object reference not set to an instance of an object.”(未将对象引用到对象的实例)。下面我们要使用扩展方法,来巧妙避免这种情况的发生。
首先新建一个类,定义为:NullUtils.cs,代码如下:
1 namespace CSharpTools.Common.Helpers 2 { 3 public static class NullUtils 4 { 5 public static bool IsNull(this object o) 6 { 7 return o == null; 8 } 9 } 10 }
然后,调用时,就可以如下做:
首先,引入命名空间:
using CSharpTools.Common.Helpers;
然后,如下调用:
1 if (o.IsNull()) 2 { 3 Console.WriteLine("O is null, we should invoke its methods or properties!"); 4 } 5 else 6 { 7 Console.WriteLine("O is not null, we can invoke it!"); 8 }
注意,在调用扩展方法的时候,会显示:"Extension methods",如下所示:
运行结果:
搞定,就这么简单。