类型比较有问题(来自系统反射)

Trouble with type compare (from system 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"),然后迭代它们的 public 方法。

这工作正常,但给我带来了很多我不想要的属性。我只想要 return "ActionResult" 或 "JsonResult".

的方法

问题出在 if (item.ReturnParameter.GetType()==...) ,我在调试模式下看到 return 类型是 ActionResult,但条件为假...我不明白问题出在哪里。

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

你想做的是if (item.ReturnParameter.ParameterType == typeof(ActionResult)) { ... }

ReturnParameter 上的 GetType 将要 return typeof(ParameterInfo)(即 ReturnParameter 的类型)

我相信您想要的是 ParameterType,这将是 return 值的类型。