2022-03-28
今天梳理一下 如何判断一个类中 是否已经使用了某个 [Attribute]
为了符合“公共语言规范(CLS)”的要求,所有的自定义的Attribute都必须继承System.Attribute。
在.NET 4.0(当然也包括4.0以前的版本)下,用反射判断某个方法是否运用了自定义Attribute时,可以通过调用MethodInfo的IsDefined()方法进行确认。当然,IsDefined()方法事实上定义在MethodInfo的父类MemberInfo中,但它仅仅被定义为抽象方法,真正的实现是在MethodInfo的子类DynamicMethod中。调用方式如下所示:
methodInfo.IsDefined(typeof(MyAttribute), false)
IsDefined的解释如下:
应用实例:
var t = obj.GetType();
//由于我们只在Property设置了Attibute,所以先获取Property
var properties = t.GetProperties();
foreach (var property in properties)
{
//这里只做一个stringlength的验证,这里如果要做很多验证,需要好好设计一下,千万不要用if elseif去链接
//会非常难于维护,类似这样的开源项目很多,有兴趣可以去看源码。
if (!property.IsDefined(typeof(StringLengthAttribute), false)) continue;
}
注意点:
程序集使用GetExportedTypes(),方式获取出来的时候去IsDefined 永远都是false
另外一种判断是否使用对应特性的方式:
private static bool IsAppliedWith(this MethodInfo methodInfo, Type attributeType, string attributeName)
{
return methodInfo.GetCustomAttributes(attributeType, false).ToString().Contains(attributeName);
}