簡體   English   中英

在linq中處理空引用異常

[英]Handling null reference exception in linq

考慮以下

var x= doc.Descendants("a").Where(p => p.Attributes["itemprop"].Value.Contains("image")).FirstOrDefault().Attributes["href"].Value;

后代可能會返回null

哪里可能返回null

值可能返回null

屬性可能為null等。

嘗試捕獲我唯一的選項,使用linq語法將變量設置為null以避免空引用異常,我只想將變量設置為null並且我不想將其拆分並使用多個if語句來檢查?

try
{
  x= doc.Descendants("a").Where(p => p.Attributes["itemprop"].Value.Contains("image")).FirstOrDefault().Attributes["href"].Value;
}
catch
{
  x=null;
}

Descendants can't return null它總是返回IEnumerable<T>

Where can't return null它返回IEnumerable<T>

Attributes might Be null yes但您可以避免使用可以使用的值(string)p.Attributes["itemprop"]而不是p.Attributes["itemprop"].Value

所以你可以把你的查詢寫成:

string val;

var x= doc.Descendants("a")
           .Where(p => (((string)p.Attributes["itemprop"]) ?? string.Empty)
                              .Contains("image"))
           .FirstOrDefault();
if(x != null)
{
    val = (string)Attributes["href"];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM