問題描述
空傳播運算符/條件訪問表達式tagged/c%23-6.0" class="post-tag" title="show questions tagged 'c#-6.0'" rel="tag">c#-6.0 看起來非常方便.但我很好奇它是否有助于解決檢查子成員是否為空然后在 if 塊內(nèi)對所述子成員調(diào)用布爾方法的問題:
The Null propagating operator / Conditional access expression coming in c#-6.0 looks like quite a handy feature. But I'm curious if it will help solve the problem of checking if a child member is not null and then calling a Boolean method on said child member inside an if block:
public class Container<int>{
IEnumerable<int> Objects {get;set;}
}
public Container BuildContainer()
{
var c = new Container();
if (/* Some Random Condition */)
c.Objects = new List<int>{1,2,4};
}
public void Test()
{
var c = BuildContainer();
//Old way
if ( null != c && null != c.Objects && c.Objects.Any())
Console.Write("Container has items!");
//C# 6 way?
if (c?.Object?.Any())
Console.Write("Container has items!");
}
c?.Object?.Any()
會編譯嗎?如果傳播運算符短路(我認為這是正確的術語)為空,那么您有 if (null)
,這是無效的.
Will c?.Object?.Any()
compile? If the propagating operator short circuits (I assume that's the right term) to null then you have if (null)
, which isn't valid.
C# 團隊會解決這個問題還是我錯過了空傳播運算符的預期用例?
Will the C# team address this concern or am I missing the intended use case for the null propagating operator?
推薦答案
這樣不行.您可以跳過解釋并查看下面的代碼:)
It won't work this way. You can just skip the explanation and see the code below :)
如您所知 ?.
如果子成員為 null,運算符將返回 null.但是如果我們嘗試獲取一個不可為空的成員,比如 Any()
方法,它返回 bool
會發(fā)生什么?答案是編譯器會將返回值包裝"在 Nullable<>
中.例如,Object?.Any()
會給我們 bool?
(即 Nullable
),而不是 bool代碼>.
As you know ?.
operator will return null if a child member is null. But what happens if we try to get a non-nullable member, like the Any()
method, that returns bool
? The answer is that the compiler will "wrap" a return value in Nullable<>
. For example, Object?.Any()
will give us bool?
(which is Nullable<bool>
), not bool
.
唯一不允許我們在 if
語句中使用這個表達式的是它不能被隱式轉(zhuǎn)換為 bool
.但是您可以明確地進行比較,我更喜歡像這樣與 true
進行比較:
The only thing that doesn't let us use this expression in the if
statement is that it can't be implicitly casted to bool
. But you can do comparison explicitly, I prefer comparing to true
like this:
if (c?.Object?.Any() == true)
Console.Write("Container has items!");
感謝@DaveSexton 還有另一種方式:
if (c?.Object?.Any() ?? false)
Console.Write("Container has items!");
但對我來說,與 true
的比較似乎更自然:)
But as for me, comparison to true
seems more natural :)
這篇關于C# Null 傳播運算符/條件訪問表達式 &如果塊的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!