您可以使用以下方式将XML属性值解析回枚举类型:
var value = Enum.Parse(typeof(Fuel), "B");
但我不认为你会用你的 "特殊" 值(3
、a/
等)走得太远。
为什么不把你的枚举定义为
enum Fuel
{
Benzine,
Diesel,
Three,
ASlash,
}
如何编写一个静态方法将字符串转换为枚举成员?
实现该方法的一种方式是向枚举成员添加自定义属性,包含它们的字符串表示形式 - 如果一个值在枚举中没有精确对应项,则查找带有该属性的成员。
创建这样的属性很容易:
public class StringValueAttribute : Attribute
{
public string Value { get; private set; }
public StringValueAttribute(string value)
{
Value = value;
}
}
然后你可以在枚举中使用它们:
enum Fuel
{
[StringValue("B")]
Benzine,
[StringValue("D")]
Diesel,
[StringValue("3")]
Three,
[StringValue("/")]
Slash,
}
这两种方法将帮助您将字符串解析为所选枚举成员:
public static object Parse(Type type, string stringValue)
{
return Parse(type, stringValue, false);
}
public static object Parse(Type type, string stringValue, bool ignoreCase)
{
object output = null;
string enumStringValue = null;
if (!type.IsEnum)
{
throw new ArgumentException(String.Format("Supplied type must be an Enum. Type was {0}", type));
}
foreach (FieldInfo fi in type.GetFields())
{
var attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[];
if (attrs != null && attrs.Length > 0)
{
enumStringValue = attrs[0].Value;
}
if (string.Compare(enumStringValue, stringValue, ignoreCase) == 0)
{
output = Enum.Parse(type, fi.Name);
break;
}
}
return output;
}
顺带一提:这是另一种方式的相反情况 ;)
public static string GetStringValue(Enum value)
{
string output = null;
Type type = value.GetType();
if (StringValues.ContainsKey(value))
{
output = ((StringValueAttribute) StringValues[value]).Value;
}
else
{
FieldInfo fi = type.GetField(value.ToString());
var attributes = fi.GetCustomAttributes(typeof(StringValueAttribute), false);
if (attributes.Length > 0)
{
var attribute = (StringValueAttribute) attributes[0];
StringValues.Add(value, attribute);
output = attribute.Value;
}
}
return output;
}