【发布时间】:2011-05-05 20:52:49
【问题描述】:
可能重复:
Shortcut for “null if object is null, or object.member if object is not null”
有些语言有一个安全的导航操作符,让您不必担心空引用异常。
语言示例Groovy:
String lname = person.Name.ToLowerCase(); //throws exception if Name is null
String lname = person.Name?.ToLowerCase();//lname will be null if Name was null
如何在 C# 中完成类似的操作?到目前为止,我的解决方案是这样的扩展方法:
public static T o<T>(this T obj) where T : new()
{
return obj != null ? obj : new T();
}
//used like: String lname = person.o().Name; //returns null if person was null
但是,这只在某些情况下有效。
【问题讨论】:
-
在写这篇文章的时候,C# 6 中其实已经计划了这样一个特性:见.NET Compiler Platform ("Roslyn"): Language feature status: Null propagating operator
?.
标签: c#