简体   繁体   English

如果XElement上不存在XAttribute默认值

[英]XAttribute default value if not existing on XElement

Is there an easier/better way to return a default value if a XAttribute on a XElement is not existing?: 如果XElement上的XAttribute不存在,是否有更简单/更好的方法来返回默认值?:

I'm trying to write this in a shorter way (cause it's a two-liner): 我试图以更短的方式写这个(因为它是一个双线):

var a = root.Attribute("testAttribute");
var v = (a == null ? "" : a.Value);

My approach: via an extension method: 我的方法:通过扩展方法:

public static XAttribute Attribute(this XElement obj, string name, string defaultValue)
{
    if (obj.Attribute(name) == null)
        return new XAttribute(name, defaultValue);
    return obj.Attribute(name);
}

var v = root.Attribute("testAttribute", "").Value;

Will this have any side-effects like a massive negative speed impact ? 这会产生任何副作用,如大规模的负面速度影响吗? Is there any better way to do that? 有没有更好的方法呢?

There's a much easier way to do that: 有一个更容易的方法来做到这一点:

var v = (string) root.Attribute("testAttribute") ?? "";

The explicit conversion from XAttribute to string returns null if the input XAttribute is null. 从显式转换XAttributestring返回null ,如果输入XAttribute为空。 The null-coalescing operator then effectively supplies the default value of an empty string. 然后,空合并运算符有效地提供空字符串的默认值。

Of course, you can still write your extension method, but I'd do it in terms of the above. 当然,您仍然可以编写扩展方法,但我会按照上述方法编写。 I'd also change the name parameter to be of type XName instead of string , for more flexibility. 我还将name参数更改为XName类型而不是string ,以获得更大的灵活性。

I needed a similar thing in my project. 我的项目中需要类似的东西。 I created a custom attribute 我创建了一个自定义属性

[AttributeUsage(AttributeTargets.Property)]
public class DefaultValue : Attribute
{
 public string ElementName {get; set;}
 public string AttributeName {get; set;}
 public object DefaultValue {get; set;}

public object GetValue(XElement element)
{
  var v = root.Attribute(AttributeName);
 if(v!= null)
  return v.value;
 else
  return DefaultValue
}
}

I used this attribute over all the properties with similar usage 我在具有类似用法的所有属性上使用了此属性

[DefaultValue(ElementName="elementName",AttributeName="attri",DefaultValue="Name")]
public string Prop{get; set;}

I get the value by invoking a method of this attribute 我通过调用此属性的方法获取值

var attribute = propertyInfo.GetCustomAttribute(typeof(DefaultValue),false);
var value = attribute.GetValue(element);

Hope this helps 希望这可以帮助

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

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