简体   繁体   中英

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:

  <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.

I'm new to LINQ,plz help.

You are accessing only the emailsetting element, which doesn't have an attribute named server or port .
You need to get the attributes from the smtp child element.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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