简体   繁体   中英

.NET Flag Enum get Attributes from values

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;

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