【问题标题】:Trouble with type compare (from system reflection)类型比较问题(来自系统反射)
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢!作品。你更快,但我给了另一个人答案以增加他的分数;)sry。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-20
      • 1970-01-01
      • 1970-01-01
      • 2020-12-11
      相关资源
      最近更新 更多