[英]C# coalesce operator Throws
我有一個帶字符串屬性的類。 我在讀取它時使用coalesce運算符,因為它可能為null,但它仍然會拋出一個NullRefrenceExeption。
string name = user.Section.ParentSection.Name ?? string.Empty;
更具體地說,它的“.ParentSection”是空的,因為它甚至沒有“.name”? 如果是這種情況,我應該先用if塊測試“.ParentSection”嗎?
我假設有一些關於Coalesce運算符的東西,我不明白,希望有人可以了解這里出了什么問題。
更具體地說,它的“.ParentSection”是空的,因為它甚至沒有“.name”?
是。
如果是這種情況,我應該先用if塊測試“.ParentSection”嗎?
是。
您需要檢查Section
和ParentSection
是否為空。 您可以為此使用if語句或編寫如下的擴展方法:
public static class MaybeMonad
{
public static TOut With<TIn, TOut>(this TIn input, Func<TIn, TOut> evaluator)
where TIn : class
where TOut : class
{
if (input == null)
{
return null;
}
else
{
return evaluator(input);
}
}
}
您可以像這樣使用此方法:
string name = user.With(u => u.Section)
.With(s => s.ParentSection)
.With(p => p.Name) ?? string.Empty;
我認為它比帶有很多&&
的if語句更清晰。
進一步閱讀: http : //www.codeproject.com/Articles/109026/Chained-null-checks-and-the-Maybe-monad
您需要檢查user
, user.Section
或user.Section.ParentSection
是否為null,然后才能對user.Section.ParentSection
的屬性使用null合並運算符。
如果訪問的任何對象為null
則嵌套屬性訪問不安全,這將拋出NullReferenceException
。 您必須顯式測試外部對象不為null。
例如:
string name = string.Empty;
if(user!=null && user.Section!=null && user.Section.ParentSection !=null)
name = user.Section.ParentSection.Name ?? string.Empty;
一般來說,我會盡量避免嵌套訪問屬性,你違反了得墨忒耳法則 。 一些重構可能首先使這不必要。
??
運算符檢查左側是否為空,如果是,則返回右側,如果不是左側則返回。 在您的情況下,左側是對象user.Section.ParentSection
的“Name”屬性,這是null。
在這些情況下,要么考慮什么可能是null或做這樣的事情:
string name = user == null
|| user.Section == null
|| user.ParentSection == null
|| user.Section.ParentSection.Name == null
? string.Empty
: user.Section.ParentSection.Name;
(是的,我知道這很難看)
機會是user
或user
user.Section
或user.Section.ParentSection
是空值。
??
運算符不會阻止檢查:
if (user != null && user.Section != null && user.Section.ParentSection != null){
確保字符串屬性的所有內容都有效且存在,那么你可以使用??
。 無論你嘗試多少次,都不能調用(null).Name
。
是的,在檢查Name
之前,您需要檢查Section
或ParentSection
是否為空
最好做這樣的事情:
if(user!=null && user.Section!=null && user.Section.ParentSection!=null)
{
string name = user.Section.ParentSection.Name ?? string.Empty;
}
null合並運算符采用如下語句:
a = b ?? c;
這說的是“評估b;如果它具有非空值,則將其分配給a。否則將c的值賦給a”。
但是在您的 b中,您使用的用戶對象可能為null,其子對象可能為null,其父段屬性可能為null,其name屬性可能為null。 如果您想檢查所有這些(通常是您應該),那么您可以執行以下操作:
string name = string.Empty;
if (user != null &&
user.Section != null &&
user.Section.ParentSection != null)
{
name = user.Section.ParentSection.Name ?? string.Empty;
}
一旦IF檢查失敗,它就不會進一步檢查,因此當你假設一個對象存在然后嘗試訪問它的一個屬性時你就不會得到NullReferenceException。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.