有什么方法可以像下面这样在 C# 中定义枚举?
public enum MyEnum : string
{
EnGb = "en-gb",
FaIr = "fa-ir",
...
}
好的,根据埃里克的方法和链接,我正在使用它来检查提供的描述中的有效值:
public static bool IsValidDescription(string description)
{
var enumType = typeof(Culture);
foreach (Enum val in Enum.GetValues(enumType))
{
FieldInfo fi = enumType.GetField(val.ToString());
AmbientValueAttribute[] attributes = (AmbientValueAttribute[])fi.GetCustomAttributes(typeof(AmbientValueAttribute), false);
AmbientValueAttribute attr = attributes[0];
if (attr.Value.ToString() == description)
return true;
}
return false;
}
有什么改进吗?
另一种不高效但提供枚举功能的替代方法是使用属性,如下所示:
public enum MyEnum
{
[Description("en-gb")]
EnGb,
[Description("fa-ir")]
FaIr,
...
}
还有一些类似扩展方法的东西,这是我使用的:
public static string GetDescription<T>(this T enumerationValue) where T : struct
{
var type = enumerationValue.GetType();
if (!type.IsEnum) throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");
var str = enumerationValue.ToString();
var memberInfo = type.GetMember(str);
if (memberInfo != null && memberInfo.Length > 0)
{
var attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs != null && attrs.Length > 0)
return ((DescriptionAttribute) attrs[0]).Description;
}
return str;
}
然后你可以这样调用它:
MyEnum.EnGb.GetDescription()
如果它有描述属性,你会得到它,如果没有,你会得到 .ToString()
版本,例如“EnGb”
。我有这样的东西的原因是直接在 Linq-to-SQL 对象上使用枚举类型,但能够在 UI 中显示漂亮的描述。我不确定它是否适合您的情况,但可以将其扔掉。