您可以使用以下方法将 xml 属性值解析回枚举类型:
var value = Enum.Parse(typeof(Fuel), "B");
但我认为你的“特殊”价值观不会走得太远(3、a/ 等)。
你为什么不把你的枚举定义为
enum Fuel
{
Benzine,
Diesel,
// ...
Three,
ASlash,
// ...
}
并编写一个静态方法将字符串转换为枚举成员?
在实现这种方法时您可以考虑的一件事是将自定义属性添加到包含其字符串表示的枚举成员中 - 如果一个值在枚举中没有精确对应项,则查找具有该属性的成员.
创建这样的属性很容易:
/// <summary>
/// Simple attribute class for storing String Values
/// </summary>
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,
// ...
}
这两种方法将帮助您将字符串解析为您选择的枚举成员:
/// <summary>
/// Parses the supplied enum and string value to find an associated enum value (case sensitive).
/// </summary>
public static object Parse(Type type, string stringValue)
{
return Parse(type, stringValue, false);
}
/// <summary>
/// Parses the supplied enum and string value to find an associated enum value.
/// </summary>
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));
}
//Look for our string value associated with fields in this enum
foreach (FieldInfo fi in type.GetFields())
{
//Check for our custom attribute
var attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[];
if (attrs != null && attrs.Length > 0)
{
enumStringValue = attrs[0].Value;
}
//Check for equality then select actual enum value.
if (string.Compare(enumStringValue, stringValue, ignoreCase) == 0)
{
output = Enum.Parse(type, fi.Name);
break;
}
}
return output;
}
当我这样做的时候:这是相反的;)
/// <summary>
/// Gets a string value for a particular enum value.
/// </summary>
public static string GetStringValue(Enum value)
{
string output = null;
Type type = value.GetType();
if (StringValues.ContainsKey(value))
{
output = ((StringValueAttribute) StringValues[value]).Value;
}
else
{
//Look for our 'StringValueAttribute' in the field's custom attributes
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;
}