c# - 我的枚举可以有友好的名字吗?

标签 c# enums

<分区>

我有以下枚举

public enum myEnum
{
    ThisNameWorks, 
    This Name doesn't work
    Neither.does.this;
}

enum 不可能有“友好名称”吗?

最佳答案

您可以按照 Yuriy 的建议使用 Description 属性。以下扩展方法可以轻松获取给定枚举值的描述​​:

public static string GetDescription(this Enum value)
{
    Type type = value.GetType();
    string name = Enum.GetName(type, value);
    if (name != null)
    {
        FieldInfo field = type.GetField(name);
        if (field != null)
        {
            DescriptionAttribute attr = 
                   Attribute.GetCustomAttribute(field, 
                     typeof(DescriptionAttribute)) as DescriptionAttribute;
            if (attr != null)
            {
                return attr.Description;
            }
        }
    }
    return null;
}

你可以这样使用它:

public enum MyEnum
{
    [Description("Description for Foo")]
    Foo,
    [Description("Description for Bar")]
    Bar
}

MyEnum x = MyEnum.Foo;
string description = x.GetDescription();

关于c# - 我的枚举可以有友好的名字吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1415140/

相关文章:

c# - 如何使用 switch case 处理异常

c# - 将 Gtk# Textbuffer 内容保存到文件

python - 如何在 Python 中 pickle 复杂的枚举值

c++ - 检测单个枚举常量的类型

c++ - C++ 类中嵌套类型的快捷方式

c++ - 从limemicro编译lms6suite时出现枚举错误

c# - 序列化或反序列化 JSON 期间的 ASP.NET MVC4 错误 - 大数据

c# - 找不到类型或命名空间 'System'。全新安装 Visual Studio 2017

C# BackgroundWorker 不报告进度

java - 枚举设计决策的常量特定方法