C# 如何将枚举用作XName
我想使用存储值的C# 如何将枚举用作XName,c#,enums,linq-to-xml,implicit-conversion,xname,C#,Enums,Linq To Xml,Implicit Conversion,Xname,我想使用存储值的enum创建一个新的XElement或XAttribute。这两个类的构造函数都希望XName作为name和object作为content。这意味着我可以将枚举作为content传递,但我需要使用ToString()在名称中使用它。请注意,XName对string有一个隐式运算符 这项工作: new XElement(HttpStatusCode.Accepted.ToString(), (int)HttpStatusCode.Accepted) new XElement(Htt
enum
创建一个新的XElement
或XAttribute
。这两个类的构造函数都希望XName
作为name
和object
作为content
。这意味着我可以将枚举作为content
传递,但我需要使用ToString()
在名称中使用它。请注意,XName
对string
有一个隐式运算符
这项工作:
new XElement(HttpStatusCode.Accepted.ToString(), (int)HttpStatusCode.Accepted)
new XElement(HttpStatusCode.Accepted.ToString(), HttpStatusCode.Accepted)
这不起作用:
new XElement(HttpStatusCode.Accepted, (int)HttpStatusCode.Accepted)
对于如何使用enum
设置XElement
的名称,有何建议
谢谢。我能想到的一个解决方案是创建一个实用方法,该方法将接受一个对象并将其转换为XName
,并创建相应的元素/属性。比如:
private static XElement NewElement(Enum name, params object[] content)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
return new XElement(name.ToString(), content);
}
枚举不能隐式转换为字符串
C#目前也没有能力定义扩展运算符
扩展方法可以简化这一点:
public static class EnumXmlExtensions
{
public static XElement EncodeXElement(this Enum @enum)
{
return new XElement(@enum.ToString());
}
}
用法:
HttpStatusCode.Accepted.EncodeXElement(); // <Accepted />
HttpStatusCode.Accepted.EncodeXElement();// @enum.ToString()
有效且较短。我看到它的实现使用了InternalFormat()
,后者反过来使用GetName()
。