代码之家  ›  专栏  ›  技术社区  ›  Edward Tanguay

我怎么用?把这两条线合并成一条?

c#
  •  1
  • Edward Tanguay  · 技术社区  · 16 年前

    我想要两个 属性分配 下面的行组成一行,因为我将把它们构建成一个应用程序,在这个应用程序中它们将是众多的。

    有没有一种方法可以用一行优雅的C来表达这两行,也许用A??像这样的操作员?

    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();
    
            }
        }
    }
    
    6 回复  |  直到 13 年前
        1
  •  4
  •   Ryan Versaw    16 年前

    当然可以!

    只要这样做:

    string lastNameDisplay = (string)xml.Element("lastName").Attribute("display") ?? "NONE";
    
        2
  •  8
  •   Tim Cooper    13 年前

    当然,但是很糟糕,不优雅:

    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();
    
        3
  •  3
  •   David    16 年前

    为什么不使用一个接受Xelement并返回lastnamedisplay字符串的小助手函数呢?

        4
  •  3
  •   Ben Lings    16 年前

    你可以这样做:

    string lastNameDisplay = (xml.Element("lastName").Attribute("display") ?? new XAttribute("display", "NONE")).Value;
    
        5
  •  1
  •   Rex M    16 年前

    不完全是这样。你要找的是一个空的守卫(我想这就是它所说的),而C没有。只有在前面的对象不为空时,它才会调用被保护的属性。

        6
  •  0
  •   lc.    16 年前

    不完全是这样。最接近的方法是使用如下扩展方法:

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