In our production code, I've seen XML attributes being read using explicit XName.Get
call:
var name = element.Attribute (XName.Get ("name"));
I used to always pass a string to Attribute
:开发者_如何学Go
var name = element.Attribute ("name");
This is more readable but I wonder if there is any difference in logic or performance.
There is no difference whatsoever.
XName
has an implicit cast from string
which calls XName.Get
.
You can see this in the source:
/// <summary>
/// Converts a string formatted as an expanded XML name ({namespace}localname) to an XName object.
/// </summary>
/// <param name="expandedName">A string containing an expanded XML name in the format: {namespace}localname.</param>
/// <returns>An XName object constructed from the expanded name.</returns>
[CLSCompliant(false)]
public static implicit operator XName(string expandedName) {
return expandedName != null ? Get(expandedName) : null;
}
Well, there are two parts to this:
Are they calling the same Attribute
method?
Yes. There's only one XElement.Attribute
method, with an XName
parameter, which means that in the latter case you are using the implicit string to XName
conversion.
Does the implicit string to XName
conversion do the same as XName.Get
?
This isn't guaranteed - the documentation doesn't mention it. But I have no reason to doubt SLaks' analysis that the current implementation is the same.
Personally I always either use the conversion from string to XName
or the addition operator between XNamespace
and string to get an XName
. I can't remember the last time I referred to it explicitly.
The conversions available are one of the beautiful things about LINQ to XML - it seems pointless to ignore them, IMO.
精彩评论