Is there an easier/better way to return a default value if a XAttribute on a XElement is not existing?:

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

其他提示

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归因
不隶属于 StackOverflow
scroll top