C # - check for attribute on enumeration element

I have the following situation:

enum Header { Sync, [OldProtocol] Keepalive, Ping, [OldProtocol] Auth, [OldProtocol] LoginData //... } 

I need to get an array of elements on which OldProtocolAttribute is defined. I noticed that the Attribute.IsDefined() method and its overloads do not seem to support this situation.

My question is:

  • Is there a way to solve the problem without using typeof(Header).GetField() in any part of the solution?
  • If not, what is the best way to solve it?
+8
enums c # attributes elements defined
source share
2 answers

As far as I know, you should get the attribute from the field. You should use:

 var field = typeof(Header).GetField(value.ToString()); var old = field.IsDefined(typeof(OldProtocolAttribute), false); 

Or to get the whole array:

 var attributeType = typeof(OldProtocolAttribute); var array = typeof(Header).GetFields(BindingFlags.Public | BindingFlags.Static) .Where(field => field.IsDefined(attributeType, false)) .Select(field => (Header) field.GetValue(null)) .ToArray(); 

Obviously, if you need it often, you might want to cache the results.

+14
source share

Reflection is pretty much your only tool available for this. The request is not so bad though:

 var oldFields = typeof(Header).GetFields(BindingFlags.Static | BindingFlags.Public).Select(field => Attribute.IsDefined(field, typeof(OldProtocolAttribute))); 
+4
source share

All Articles