【问题标题】:Why this LINQ throws NullReferenceException?为什么这个 LINQ 会抛出 NullReferenceException?
【发布时间】:2012-07-16 09:49:55
【问题描述】:
private SmtpClient getServer()
        {
            return (from e in doc.Elements("emailsetting")
                    select new SmtpClient()
                    {
                        Host = e.Attribute("server").Value,
                        Port = Convert.ToInt32(e.Attribute("port").Value)
                    }).FirstOrDefault();
        }

xml配置文件:

  <emailsetting>
    <stmp server="10.182.182.182" port="25" />
    <from address="ithelpdest@citics.com.hk"/>
    <to address=""/>
    <cc address=""/>
  </emailsetting>

为什么会抛出异常: NullReferenceException 未处理 对象引用未设置为对象的实例。

我是 LINQ 新手,请帮助。

【问题讨论】:

  • 'smtp' 在 XML 中拼写为 'stmp'。 :)

标签: c# .net xml linq


【解决方案1】:

您仅访问emailsetting 元素,该元素没有名为serverport 的属性。
您需要从 smtp 子元素中获取属性。

试试这个:

return (from e in doc.Elements("emailsetting")
        let smtp = e.Element("smtp")
        select new SmtpClient()
        {
            Host = smtp.Attribute("server").Value,
            Port = Convert.ToInt32(smtp.Attribute("port").Value)
        }).FirstOrDefault();

【讨论】:

  • +1,但请注意拼写错误:OP 在 xml 示例中使用错误的“stmp”而不是“smtp”
  • 谢谢。但是 LINQ 会返回一个对象吗?因为当我调用 Console.WriteLine(getServer().Host) 来测试 ip 时,它会抛出相同的异常
  • @user838204 你有没有考虑到你的xml中的错字?你写的是“stmp”而不是“smtp”。所以你应该改变你的xml以使用“smtp”。另外,doc 可能为空吗?
  • 我注意到错字并将其更改为 smtp。并且 doc 不能为空。我尝试 SmtpClient smtp = getServer();并找到 smtp=null
  • 我使用了这个:from e in doc.element("smtp") 而不是 from e in doc.Elements("emailsetting") let smtp = e.Element("smtp")
猜你喜欢
  • 1970-01-01
  • 2010-09-27
  • 2014-03-07
  • 2012-01-28
  • 1970-01-01
  • 2011-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多