简体   繁体   中英

Getting description of enum's value without using reflection

Firstly the reason behind using enums for my case is simply developing a catalog for error codes and I've been using the Description attribute to keep the actual error message. I can get the value of the Description attribute using reflections but my question is: is there another way to get the value of that attribute without using reflections? For example, there is a Enum type in C# so could that type be used instead to get the value of attributes in an enum?

**I know that developing a data model using a class is a better move, enum is an old habit and the reason why I'm insisting on it is because I just wanna know if I can get value of those attributes without reflection.

Enum is not at all an old habit. It's very useful but to discuss it here would be off-topic...

Without reflection I can only think about some kind of mapping:

class Program
{
    static void Main(string[] args)
    {
        var crazyValue = CrazyEnum.craZyValue1;
        var resonableValue = crazyValue.ToRreasonableString();
    }
}

enum CrazyEnum
{
    craZyValue1,
    CrazYvalUe2
}

static class CrazyEnumMap
{
    private static Dictionary<CrazyEnum, string> resonableStrings = new Dictionary<CrazyEnum, string>
    {
        { CrazyEnum.craZyValue1, "Hallo world!" },
        { CrazyEnum.CrazYvalUe2, "Hallo enum!" }
    };

    public static string ToRreasonableString(this CrazyEnum value)
    {
        return resonableStrings[value];
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM