在執行成員訪問之前,我已經知道空條件運算符can be used to test爲null。C#6空條件運算符 - 作爲代碼切換器?
例如:
int? length = customers?.Length; // null if customers is null
Customer first = customers?[0];
如果customers
在customers?.Length
爲null,則customers?.Length
將返回null和null
將在int? length = ...
可變
我也知道,它可以used單個原子在多線程環境中調用方法:
public void OnFoo()
{
Foo?.Invoke(this, EventArgs.Empty);
}
但
AFAIU - 如果Foo
是null
然後
Foo?.Invoke(this, EventArgs.Empty);
同樣是null
所以我們留下了
public void OnFoo()
{
null; //compilation error
}
所以我要問:
問題
似乎空條件運算符不僅用於測試空,如果有,那麼它進行更深層次的:x?.y?.c?.d
-
,但它也像代碼切換:
像這樣:
public void OnFoo()
{
Foo?.Invoke(this, EventArgs.Empty); //Let's assume Foo =null;
}
變爲
public void OnFoo()
{
}
對不起,對嗎?我沒有找到這方面的任何文件。
感謝Jon。但是:_ [如果您可以打印它,或者將其分配給一個變量,則它是一個表達式。如果你不能,這是一個聲明](https://www.quora.com/Whats-the-difference-between-a-statement-and-an-expression-in-Python)._。因爲我不能通過:var result = Foo?.Invoke(this,EventArgs.Empty);' - 然後根據他的鏈接,它是一個聲明。我的錯誤在哪裏? –
@RoyiNamir:這是關於Python,而不是C#,我懷疑它還是過於簡化。你的'var result = ...;'不會編譯,因爲'Invoke'返回'void' ...我不確定你在問什麼。 –
Jon - [我在做夢](https://github.com/ljw1004/csharpspec/blob/gh-pages/CSharp%20Language%20Specification.pdf?raw=true)?請參閱第188頁 –