我怎么用?把这两行合二为一?

Edw*_*uay 1 c#

我想将下面的两个属性赋值行放到一行中,因为我要将它们构建到一个应用程序中,它们将会很多.

有没有办法在一行优雅构造的C#中表达这两行,也许有一个?? 像这样的运营商?

string nnn = xml.Element("lastName").Attribute("display").Value ?? "";
Run Code Online (Sandbox Code Playgroud)

这是代码:

using System;
using System.Xml.Linq;

namespace TestNoAttribute
{
    class Program
    {
        static void Main(string[] args)
        {

            XElement xml = new XElement(
                new XElement("employee",
                    new XAttribute("id", "23"),
                    new XElement("firstName", new XAttribute("display", "true"), "Jim"),
                    new XElement("lastName", "Smith")));

            //is there any way to use ?? to combine this to one line?
            XAttribute attribute = xml.Element("lastName").Attribute("display");
            string lastNameDisplay = attribute == null ? "NONE" : attribute.Value;

            Console.WriteLine(xml);
            Console.WriteLine(lastNameDisplay);

            Console.ReadLine();

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Ken*_*art 8

当然,但它很可怕,不优雅:

string lastNameDisplay = xml.Element("lastName").Attribute("display") == null ? "NONE" : xml.Element("lastName").Attribute("display").Value;
Run Code Online (Sandbox Code Playgroud)

如果您愿意,可以编写扩展方法:

public static string GetValue(this XAttribute attribute)
{
    if (attribute == null)
    {
        return null;
    }

    return attribute.Value;
}
Run Code Online (Sandbox Code Playgroud)

用法:

var value = attribute.GetValue();
Run Code Online (Sandbox Code Playgroud)