c# - 枚举设置为字符串并在需要时获取字符串值

标签 c# string enums

我不知道该怎么做
我想要如下代码

enum myenum
{
    name1 = "abc",
    name2 = "xyz"
}

检查一下

if (myenum.name1 == variable)

我该怎么做?

谢谢。

最佳答案

很遗憾,这是不可能的。枚举只能有基本的底层类型(intuintshort 等)。如果您想将枚举值与其他数据相关联,请将属性应用于值(例如 DescriptionAttribute )。

public static class EnumExtensions
{
    public static TAttribute GetAttribute<TAttribute>(this Enum value)
        where TAttribute : Attribute
    {
        var type = value.GetType();
        var name = Enum.GetName(type, value);
        return type.GetField(name)
            .GetCustomAttributes(false)
            .OfType<TAttribute>()
            .SingleOrDefault();
    }

    public static String GetDescription(this Enum value)
    {
        var description = GetAttribute<DescriptionAttribute>(value);
        return description != null ? description.Description : null;
    }
}

enum MyEnum
{
    [Description("abc")] Name1,
    [Description("xyz")] Name2,
}

var value = MyEnum.Name1;
if (value.GetDescription() == "abc")
{
    // do stuff...
}

关于c# - 枚举设置为字符串并在需要时获取字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10426444/

相关文章:

php - (PHP) 使字符串小写,第一个字母除外

具有 Enum 类型属性的 WPF 用户控件

jquery - Enum JQuery 上的 $.each

swift - 修改枚举关联值

c# - "GenerateDepsFile"任务意外失败 : Missing Microsoft. DotNet.PlatformAbstractions

c# - Autofac 属性注入(inject)失败

在多个选定的下拉列表中将 PHP 数组转换为字符串

c - 使用 c 在给定的字符串文本中添加三位数字

c# - 计算反射弧

c# - 将列表框的项目保存到文本文件