Skip to main content
 首页 » 编程设计

c#之可能的 NullReferenceException

2024年02月23日14tintown

例如这段代码:

private void LoadComments(Member member, XElement commentsXml) 
{ 
    member.Comments = (from comment in commentsXml.Descendants("comment") 
                     select new Comment() 
                     { 
                         ID = comment.Element("id").Value, 
                         Text = comment.Element("text").Value, 
                         Date = comment.Element("date").Value, 
                         Owner = comment.Element("user").Element("name").Value 
                     }).ToList(); 
} 

ReSharper 警告我 comment.Element 行可能存在 NullReferenceException。没错,异常被触发了。

关于如何避免这种情况的任何建议?那如果返回null呢,就返回一个空字符串,这可能吗?

请您参考如下方法:

我更愿意为它添加一个扩展类:

public static class XElementExtension 
{ 
   public static string GetValue(this XElement input) 
   { 
      if (input == null) 
        return null; 
      return input.Value as T; 
   } 
 
   public static XElement GetSubElement(this XElement element, string id) 
   { 
      if (element == null) 
        return null; 
      return element.Element(id); 
   } 
} 

并将其用作:

ID = comment.Element("id").GetValue() 

或

Owner = comment.Element("user").GetSubElement("name").GetValue() 

还有其他方法如:

http://www.codeproject.com/KB/cs/maybemonads.aspx