簡體   English   中英

我如何使用?? 將這兩行合並為一個?

[英]How can I use ?? to combine these two lines into one?

我想將下面的兩個屬性分配行合並為一行,因為我要將它們構建到一個應用程序中,它們將是無數的。

有沒有一種方法可以在優雅構造的C#的一行中表達這兩行,也許是用? 像這樣的運算符?

string nnn = xml.Element("lastName").Attribute("display").Value ?? "";

這是代碼:

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

        }
    }
}

可以,但是很糟糕,並不優雅:

string lastNameDisplay = xml.Element("lastName").Attribute("display") == null ? "NONE" : xml.Element("lastName").Attribute("display").Value;

如果願意,可以編寫擴展方法:

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

    return attribute.Value;
}

用法:

var value = attribute.GetValue();

你當然可以!

只要這樣做:

string lastNameDisplay = (string)xml.Element("lastName").Attribute("display") ?? "NONE";

為什么不使用一個小的輔助函數,該函數需要一個XElement並返回lastNameDisplay字符串?

您可以這樣做:

string lastNameDisplay = (xml.Element("lastName").Attribute("display") ?? new XAttribute("display", "NONE")).Value;

不完全是。 您正在尋找的是null防護(我想這就是它的名稱),而c#沒有。 如果前面的對象不為null,則它將僅調用guarded屬性。

不完全的。 您將獲得的最接近的擴展方法如下所示:

public static string ValueOrDefault(this XAttribute attribute, string Default)
{
    if(attribute == null)
        return Default;
    else
        return attribute.Value;
}

然后,您可以將兩行縮短為:

string lastNameDisplay = xml.Element("lastName").Attribute("display").ValueOrDefault("NONE");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM