How to tell the difference between a Flags enum and ordinary enum? [duplicate]

StackOverflow https://stackoverflow.com/questions/15131387

  •  16-03-2022
  •  | 
  •  

Вопрос

Is there any way to test reflectively if an enum is a [Flags] enum or if it's a regular enum?

I need the application to behave slightly differently if the enum is a Flags enum than if it's not a Flags enum.

Это было полезно?

Решение

You can test for attribute existence via reflection:

System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t);
var isFlags = attrs.Any(attr => attr is FlagsAttribute);

Or:

var isFlags = typeof(MyEnum).GetCustomAttributes<FlagsAttribute>().Any();

See: http://msdn.microsoft.com/en-us/library/z919e8tw(v=vs.80).aspx

[OP Edit:]

this worked, but the syntax is slightly wrong. This is correct:

var isFlags = myEnum.GetType()
    .GetCustomAttributes(typeof(FlagsAttribute), false).Any();

Другие советы

You can get the attributes of the enum with reflection and see if the FlagsAttribute is used.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top