【发布时间】:2012-01-11 09:37:35
【问题描述】:
我有一个示例类
public class MyClass{
ActionResult Method1(){
....
}
[Authorize]
ActionResult Method2(){
....
}
[Authorize]
ActionResult Method3(int value){
....
}
}
现在我想要写一个返回真/假的函数,可以像这样执行
var controller = new MyClass();
Assert.IsFalse(MethodHasAuthorizeAttribute(controller.Method1));
Assert.IsTrue(MethodHasAuthorizeAttribute(controller.Method2));
Assert.IsTrue(MethodHasAuthorizeAttribute(controller.Method3));
我到了这个地步
public bool MethodHasAuthorizeAttribute(Func<int, ActionResult> function)
{
return function.Method.GetCustomAttributes(typeof(AuthorizeAttribute), false).Length > 0;
}
适用于方法 3。现在我怎样才能以一种将字符串和类也作为参数的方式来实现这个泛型?
【问题讨论】:
-
你想在一个泛型方法中检查类、方法或属性是否有这样的属性吗?
-
你只是想知道一个方法是否应用了某种类型的属性?
-
我想检查方法是否设置了特定的属性,但我不想将方法名称作为字符串传递。
-
这是否缺乏性能?为每个 api 入口做反射很昂贵,不是吗?
标签: c# reflection attributes tdd assert