문제

Greetings StackOverflow,

If I've got an enum type with the Flag attribute as well as the values in this enum type with their own attributes, how can I retrieve all of the appropriate attributes?

For example:

[Flags()]
enum MyEnum
{
    [EnumDisplayName("Enum Value 1")]
    EnumValue1 = 1,
    [EnumDisplayName("Enum Value 2")]
    EnumValue2 = 2,
    [EnumDisplayName("Enum Value 3")]
    EnumValue3 = 4,
}

void Foo()
{
    var enumVar = MyEnum.EnumValue2 | MyEnum.EnumValue3;

    // get a collection of EnumDisplayName attribute objects from enumVar
    ...
}
도움이 되었습니까?

해결책

A quick and dirty way using Linq:

IEnumerable<EnumDisplayNameAttribute> attributes = 
    Enum.GetValues(typeof(MyEnum))
        .Cast<MyEnum>()
        .Where(v => enumVar.HasFlag(v))
        .Select(v => typeof(MyEnum).GetField(v.ToString()))
        .Select(f => f.GetCustomAttributes(typeof(EnumDisplayNameAttribute), false)[0])
        .Cast<EnumDisplayNameAttribute>();

Or in query syntax:

IEnumerable<EnumDisplayNameAttribute> attributes = 
    from MyEnum v in Enum.GetValues(typeof(MyEnum))
    where enumVar.HasFlag(v)
    let f = typeof(MyEnum).GetField(v.ToString())
    let a = f.GetCustomAttributes(typeof(EnumDisplayNameAttribute), false)[0]
    select ((EnumDisplayNameAttribute)a);

Alternatively, if there could possibly be multiple attributes on each field, you'll probably want to do this:

IEnumerable<EnumDisplayNameAttribute> attributes = 
    Enum.GetValues(typeof(MyEnum))
        .Cast<MyEnum>()
        .Where(v => enumVar.HasFlag(v))
        .Select(v => typeof(MyEnum).GetField(v.ToString()))
        .SelectMany(f => f.GetCustomAttributes(typeof(EnumDisplayNameAttribute), false))
        .Cast<EnumDisplayNameAttribute>();

Or in query syntax:

IEnumerable<EnumDisplayNameAttribute> attributes = 
    from MyEnum v in Enum.GetValues(typeof(MyEnum))
    where enumVar.HasFlag(v))
    let f = typeof(MyEnum).GetField(v.ToString())
    from EnumDisplayNameAttribute a in f.GetCustomAttributes(typeof(EnumDisplayNameAttribute), false)
    select a;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top