首页 > 解决方案 > 获取枚举实例给定它的自定义属性的值

问题描述

最近,我尝试使用谷歌搜索并寻找答案,如何获得枚举值具有自定义属性的枚举实例。我开始输入其自定义属性的值,我想知道哪个枚举值对应。

例子:

public enum whatever
{
    [MyCustomAttribute("foo1", "foo2")]
    SOMETHING,

    [MyCustomAttribute("foo2", "foo3")]
    SOMETHING_2
}

... 属性:

public MyCustomAttribute() : Attribute
{
    string somevalue;
    string anothervalue;

    public MyCustomAttribute(string f, string f2)
    {
        somevalue = f;
        anothervalue = f2;
    }
}

我得到“foo1”作为输入,我想返回whatever.SOMETHING。

标签: c#enumsattributes

解决方案


我能够想出一个非常适合我的简单解决方案,我很惊讶我无法在任何地方找到它。

public whatever GetWhatever(string value)
    => typeof(whatever).GetEnumValues()
        .Cast<whatever>().First(val => val .GetCustomAttributeee<MyCustomAttribute>().somevalue == value);

如果你能给我一些关于我的解决方案及其问题的反馈,我会很高兴。


推荐阅读