目前,我试图确定我的程序集中的哪些“控制器”类具有使用Reflection和LINQ与它们关联的[Authorize]属性。使用LINQ和反射:如何在我的程序集中查询[Authorize]属性中的所有类?
const bool allInherited = true;
var myAssembly = System.Reflection.Assembly.GetExecutingAssembly();
var controllerList = from type in myAssembly.GetTypes()
where type.Name.Contains("Controller")
where !type.IsAbstract
let attribs = type.GetCustomAttributes(allInherited)
where attribs.Contains("Authorize")
select type;
controllerList.ToList();
此代码几乎可行。
如果我逐步跟踪LINQ语句,我可以看到当我“悬停”我在LINQ语句中定义的“attribs”范围变量填充了单个Attribute并且该属性碰巧属于AuthorizeAttribute类型。它看起来有点像这样:
[-] attribs | {object[1]}
[+] [0] | {System.Web.Mvc.AuthorizeAttribute}
显然,这条线在我的LINQ说法是错误的:
where attribs.Contains("Authorize")
,我应该怎么写那里,而不是检测是否“attribs”包含AuthorizeAttribute类型或不?
Riiiight。 “任何”方法。我知道“Contains”是错误的(因为Intellisense不允许我写Lambda表达式,但我无法弄清楚从列表中选择哪种方法...) - 谢谢,伙计。我知道这是一个简单的问题,有人可以立即指出。 – Pretzel 2010-06-10 17:04:39
@Pretzel没问题 – luke 2010-06-10 17:08:39