类型比较麻烦(来自系统反射)

时间:2015-03-12 14:37:49

标签: c# asp.net-mvc reflection

我有以下代码:

  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,但条件是false ...我不明白哪里是问题。

2 个答案:

答案 0 :(得分:3)

item.ReturnParameter.GetType()返回ReturnParameter对象的类型,即System.Reflection.ParameterInfo或从中继承的类型。

您要做的是if (item.ReturnParameter.ParameterType == typeof(ActionResult)) { ... }

答案 1 :(得分:1)

ReturnParameter上的GetType将返回typeof(ParameterInfo)(即ReturnParameter的类型)

我相信你想要的是ParameterType,这将是返回值的类型。