简体   繁体   English

为什么此LINQ抛出NullReferenceException?

[英]Why this LINQ throws NullReferenceException?

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();
        }

The xml config file: xml配置文件:

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

Why throws the exception: NullReferenceException was unhandled Object reference not set to an instance of an object. 为什么抛出异常:未处理NullReferenceException对象引用未设置为对象的实例。

I'm new to LINQ,plz help. 我是LINQ的新手,请帮忙。

You are accessing only the emailsetting element, which doesn't have an attribute named server or port . 您仅在访问emailsetting元素,该元素没有名为serverport的属性。
You need to get the attributes from the smtp child element. 您需要从smtp子元素获取属性。

Try this: 尝试这个:

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM