簡體   English   中英

嘗試使用linq to xml檢索不存在的父母的孩子時避免空引用異常

[英]avoid null reference exception when trying to retrieve children of unexisting parents with linq to xml

當訪問不存在的父母的孩子元素時,是否有一種簡單的方法來避免空引用異常? 例如,我有此查詢:

            Persons = (from actor in xDoc.Root.Element(imdbns + "Cast").Elements(imdbns + "Actor")
                       select new Person { Name = (string)actor.Element(imdbns + "Person").Element(imdbns + "Name"), Role = "Actor" }).Union(
                       from director in xDoc.Root.Element(imdbns + "Directors").Elements(imdbns + "Person")
                       select new Person { Name = (string)director.Element(imdbns + "Name"), Role = "Director" }).Union(
                       from writer in xDoc.Root.Descendants(imdbns + "Writer")
                       select new Person { Name = (string)writer.Element(imdbns + "Person").Element(imdbns + "Name"), Role = "Writer" }).ToList()

它將三個元素(演員,作家,導演)統一為一個對象Person。 問題是我事先不知道元素“ Cast”或元素“ Directors”是否存在。 這些元素是我需要訪問的最終元素的父元素,如果它們不存在,我將得到一個null引用異常。 所以我的問題是:是否必須將查詢分解為“ if!= null then”不可讀的序列集,還是有更方便的方法?

謝謝

您可以先進行檢查。 遵循以下原則

if(xDoc.Root.Element(imdbns + "Cast") != null && xDoc.Root.Element(imdbns + "Directors" != null)
{
   Persons = (from actor in ...
}

暫無
暫無

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

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