C# 枚举能否使用友好的名称?
正如您所发现的,C# 枚举成员只能使用文字名称,并以下划线作为分隔符。但是,有一种方法可以为您的枚举分配“友好的名称”。
解决方案:Description 属性
您可以使用 DescriptionAttribute
属性为每个枚举成员提供更友好的描述。以下是一个简化检索描述的扩展方法:
public static string GetDescription(this Enum value) { Type type = value.GetType(); string name = Enum.GetName(type, value); FieldInfo field = type.GetField(name); DescriptionAttribute attr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute; return attr != null ? attr.Description : null; }
使用方法:
将 DescriptionAttribute
应用于每个枚举成员并提供所需的友好名称:
public enum MyEnum { [Description("此名称有效")] ThisNameWorks, [Description("此名称无效")] ThisNameDoesntWork, [Description("这个也不行")] NeitherDoesThis }
要检索友好名称:
MyEnum x = MyEnum.ThisNameWorks; string description = x.GetDescription();
以上是我可以在 C# 中为枚举成员指定友好名称吗?的详细内容。更多信息请关注PHP中文网其他相关文章!