相关疑难解决方法(0)

枚举的字符串表示形式

我有以下枚举:

public enum AuthenticationMethod
{
    FORMS = 1,
    WINDOWSAUTHENTICATION = 2,
    SINGLESIGNON = 3
}
Run Code Online (Sandbox Code Playgroud)

然而问题是,当我要求AuthenticationMethod.FORMS而不是id 1时,我需要"FORMS"这个词.

我找到了以下解决此问题的方法(链接):

首先,我需要创建一个名为"StringValue"的自定义属性:

public class StringValue : System.Attribute
{
    private readonly string _value;

    public StringValue(string value)
    {
        _value = value;
    }

    public string Value
    {
        get { return _value; }
    }

}
Run Code Online (Sandbox Code Playgroud)

然后我可以将此属性添加到我的枚举器:

public enum AuthenticationMethod
{
    [StringValue("FORMS")]
    FORMS = 1,
    [StringValue("WINDOWS")]
    WINDOWSAUTHENTICATION = 2,
    [StringValue("SSO")]
    SINGLESIGNON = 3
}
Run Code Online (Sandbox Code Playgroud)

当然我需要一些东西来检索StringValue:

public static class StringEnum
{
    public static string GetStringValue(Enum value)
    { …
Run Code Online (Sandbox Code Playgroud)

c# enums

897
推荐指数
19
解决办法
75万
查看次数

从Description属性获取枚举

可能重复:
通过其描述属性查找枚举值

我有一个通用的扩展方法,它Description从以下方式获取属性Enum:

enum Animal
{
    [Description("")]
    NotSet = 0,

    [Description("Giant Panda")]
    GiantPanda = 1,

    [Description("Lesser Spotted Anteater")]
    LesserSpottedAnteater = 2
}

public static string GetDescription(this Enum value)
{            
    FieldInfo field = value.GetType().GetField(value.ToString());

    DescriptionAttribute attribute
            = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))
                as DescriptionAttribute;

    return attribute == null ? value.ToString() : attribute.Description;
}
Run Code Online (Sandbox Code Playgroud)

所以我可以......

string myAnimal = Animal.GiantPanda.GetDescription(); // = "Giant Panda"
Run Code Online (Sandbox Code Playgroud)

现在,我正试图在另一个方向上找出等效函数,比如......

Animal a = (Animal)Enum.GetValueFromDescription("Giant Panda", typeof(Animal));
Run Code Online (Sandbox Code Playgroud)

.net c# enums attributes

206
推荐指数
4
解决办法
18万
查看次数

标签 统计

c# ×2

enums ×2

.net ×1

attributes ×1