[英]Finding out if an enum has the “Flags” attribute set
Using reflection, how do I determine whether an enum has the Flags attribute or not 使用反射,如何确定枚举是否具有Flags属性
so for MyColor return true 所以对于MyColor返回true
[Flags]
public enum MyColor
{
Yellow = 1,
Green = 2,
Red = 4,
Blue = 8
}
and for MyTrade return false 并为MyTrade返回false
public enum MyTrade
{
Stock = 1,
Floor = 2,
Net = 4,
}
if (typeof(MyEnum).GetCustomAttributes(typeof(FlagsAttribute), false).Length > 0)
If you are on .NET 4.5: 如果您使用的是.NET 4.5:
if (typeof(MyColor).GetCustomAttributes<FlagsAttribute>().Any())
{
}
If you just want to check if an attribute is present, without inspecting any attribute data, you should use MemberInfo.IsDefined
. 如果您只想检查某个属性是否存在,而不检查任何属性数据,则应使用
MemberInfo.IsDefined
。 It returns a bool
that indicates "whether one or more attributes of the specified type or of its derived types is applied to this member" instead of dealing with a collection of attributes. 它返回一个
bool
,指示“指定类型或其派生类型的一个或多个属性是否应用于此成员”,而不是处理属性集合。
typeof(MyColor).IsDefined(typeof(FlagsAttribute), inherit: false); // true
typeof(MyTrade).IsDefined(typeof(FlagsAttribute), inherit: false); // false
Or, if you're on .NET 4.5+: 或者,如果您使用的是.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.