問題描述
是否可以以某種方式縮短此聲明?
Is it possible to somehow shorten this statement?
if (obj != null)
obj.SomeMethod();
因為我碰巧寫了很多,這很煩人.我唯一能想到的就是實現Null Object模式,但這不是我每次都能做到的,當然也不是縮短語法的解決方案.
because I happen to write this a lot and it gets pretty annoying. The only thing I can think of is to implement Null Object pattern, but that's not what I can do every time and it's certainly not a solution to shorten syntax.
和事件類似的問題,其中
And similar problem with events, where
public event Func<string> MyEvent;
然后調用
if (MyEvent != null)
MyEvent.Invoke();
推薦答案
從 C# 6 開始,您只需使用:
From C# 6 onwards, you can just use:
MyEvent?.Invoke();
或:
obj?.SomeMethod();
?.
是空值傳播操作符,當操作數為null
時會導致.Invoke()
短路代碼>.操作數只被訪問一次,因此不存在檢查和調用之間的值變化"問題的風險.
The ?.
is the null-propagating operator, and will cause the .Invoke()
to be short-circuited when the operand is null
. The operand is only accessed once, so there is no risk of the "value changes between check and invoke" problem.
===
在 C# 6 之前,否:沒有空安全魔法,只有一個例外;擴展方法 - 例如:
Prior to C# 6, no: there is no null-safe magic, with one exception; extension methods - for example:
public static void SafeInvoke(this Action action) {
if(action != null) action();
}
現在這是有效的:
Action act = null;
act.SafeInvoke(); // does nothing
act = delegate {Console.WriteLine("hi");}
act.SafeInvoke(); // writes "hi"
在事件的情況下,這還具有消除競爭條件的優點,即您不需要臨時變量.所以通常你需要:
In the case of events, this has the advantage of also removing the race-condition, i.e. you don't need a temporary variable. So normally you'd need:
var handler = SomeEvent;
if(handler != null) handler(this, EventArgs.Empty);
但帶有:
public static void SafeInvoke(this EventHandler handler, object sender) {
if(handler != null) handler(sender, EventArgs.Empty);
}
我們可以簡單地使用:
SomeEvent.SafeInvoke(this); // no race condition, no null risk
這篇關于在 C# 中如果不為 null 的方法調用的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!