找出枚举是否设置了“标志”属性

使用reflection,如何确定枚举是否具有Flags属性

所以对于MyColor返回true

[Flags] public enum MyColor { Yellow = 1, Green = 2, Red = 4, Blue = 8 } 

并为MyTrade返回false

 public enum MyTrade { Stock = 1, Floor = 2, Net = 4, } 

如果您使用的是.NET 4.5:

 if (typeof(MyColor).GetCustomAttributes().Any()) { } 
 if (typeof(MyEnum).GetCustomAttributes(typeof(FlagsAttribute), false).Length > 0) 

如果您只想检查某个属性是否存在,而不检查任何属性数据,则应使用MemberInfo.IsDefined 。 它返回一个bool ,指示“指定类型或其派生类型的一个或多个属性是否应用于此成员”,而不是处理属性集合。

 typeof(MyColor).IsDefined(typeof(FlagsAttribute), inherit: false); // true typeof(MyTrade).IsDefined(typeof(FlagsAttribute), inherit: false); // false 

或者,如果您使用的是.NET 4.5+:

 using System.Reflection; typeof(MyColor).IsDefined(inherit: false); // true typeof(MyTrade).IsDefined(inherit: false); // false