gpt4 book ai didi

c# - 可能的 NullReferenceException

转载 作者:太空宇宙 更新时间:2023-11-03 22:17:38 24 4
gpt4 key购买 nike

例如这段代码:

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

关于c# - 可能的 NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4472472/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com