[英]Finding out if an enum has the “Flags” attribute set
使用反射,如何确定枚举是否具有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,
}
if (typeof(MyEnum).GetCustomAttributes(typeof(FlagsAttribute), false).Length > 0)
如果您使用的是.NET 4.5:
if (typeof(MyColor).GetCustomAttributes<FlagsAttribute>().Any())
{
}
如果您只想检查某个属性是否存在,而不检查任何属性数据,则应使用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<FlagsAttribute>(inherit: false); // true
typeof(MyTrade).IsDefined<FlagsAttribute>(inherit: false); // false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.