安全航行操作员在C#中? [英] Safe Navigation Operator in C#?
问题描述
可能重复:结果
<一href=\"http://stackoverflow.com/questions/3817930/shortcut-for-null-if-object-is-null-or-object-member-if-object-is-not-null\">Shortcut对于&ldquo;如果空对象为null,或者如果object.member对象不是空&rdquo;的
有些语言有一个安全的导航操作,让你不用担心空引用异常。
Some languages have a safe navigation operator that lets you not worry about null reference exceptions.
语言的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#中类似这样的东西吗?我的解决方案至今是一个扩展的方法是这样的:
How can I accomplish something similar to this in C#? My solution so far is an extension method like this:
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
然而,这只能在某些情况下。
However, this only works in some cases.
推荐答案
对于这样的情况我倾向于使用称为扩展方法 IfNotNull
:
For such cases I tend to use an extension method called IfNotNull
:
public static OUT IfNotNull<IN, OUT>(this IN v, Func<IN, OUT> f)
where IN : class where OUT : class
{
return v == null ? null : f(v);
}
更复杂的是引进的可能概念。一个例子被带到由德里克·贝利<一个href=\"http://www.lostechies.com/blogs/derickbailey/archive/2010/09/29/monads-in-c-which-part-is-the-monad.aspx\"相对=nofollow>这里。
更新:
由于 C#6 现在有一个空传播运营商其语法明智的长相酷似的Groovy之一。
As of C# 6 there is now a null-propagating operator which syntax-wise looks exactly like the Groovy one.
这篇关于安全航行操作员在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!