【发布时间】:2015-03-12 14:37:48
【问题描述】:
我有以下代码:
public ActionResult Test()
{
Assembly asm = Assembly.GetExecutingAssembly();
string name;
string text = "Controller";
foreach (var item in asm.GetTypes()
.Where(type => typeof(Controller).IsAssignableFrom(type)) //filter controllers
.SelectMany(type => type.GetMethods())
.Where(method => method.IsPublic && !method.IsDefined(typeof(NonActionAttribute))))
{
name = item.DeclaringType.Name;
//check if the word in text is in the end of the controller name:
if (name.LastIndexOf(text) > 0 && name.LastIndexOf(text) + text.Length == name.Length)
{
System.Diagnostics.Debug.WriteLine(item.Name +" / " + item.DeclaringType.Name);
if (item.ReturnParameter.GetType() == typeof(ActionResult) || item.ReturnParameter.GetType() == typeof(JsonResult))
{
System.Diagnostics.Debug.WriteLine("YES--> "+item.Name + " / " + item.DeclaringType.Name);
}
}
}
return View();
}
这假设给我带来所有以字符串“Controller”结尾的控制器(例如“HelpController”),然后迭代它们的公共方法。
这很好用,但给我带来了许多我不想要的属性。我只想要返回“ActionResult”或“JsonResult”的方法。
问题出在 if (item.ReturnParameter.GetType()==...) 中,我在调试模式下看到返回类型为 ActionResult,但条件为假...我不明白在哪里是问题所在。
【问题讨论】:
标签: c# asp.net-mvc reflection