【问题标题】:How to get methods declared in Base class using Reflection?如何使用反射获取基类中声明的方法?
【发布时间】:2015-07-02 04:46:27
【问题描述】:

我正在尝试在 Windwos 8 商店应用程序中使用反射调用方法。我尝试使用 this.GetType().GetTypeInfo().DeclaredMethods 从基类方法中获取所有方法的列表。

var methodList = base.GetType().GetTypeInfo().DeclaredMethods;

我可以得到所有 在子类中声明的方法并调用它们。但我无法获取基类中定义的方法列表。
这种方法有什么问题? 此项目使用 .Net for Windows 商店构建

【问题讨论】:

  • 目前还不清楚您到底要做什么,因为您似乎混淆了基类和子类。 this.GetType().GetTypeInfo().DeclaredMethods 将为您提供 CHILD CLASS 方法。

标签: c# .net c#-4.0 reflection windows-store-apps


【解决方案1】:
GetType().GetRuntimeMethods()

这个方法给了我想要的。 在运行时获取对象内部存在的所有方法。

【讨论】:

    【解决方案2】:

    您必须手动完成:

    public static class TypeInfoEx
    {
        public static MethodInfo[] GetMethods(this TypeInfo type)
        {
            var methods = new List<MethodInfo>();
    
            while (true)
            {
                methods.AddRange(type.DeclaredMethods);
    
                Type type2 = type.BaseType;
    
                if (type2 == null)
                {
                    break;
                }
    
                type = type2.GetTypeInfo();
            }
    
            return methods.ToArray();
        }
    }
    

    然后

    Type type = typeof(List<int>);
    TypeInfo typeInfo = type.GetTypeInfo();
    MethodInfo[] methods = typeInfo.GetMethods();
    

    【讨论】:

      【解决方案3】:

      注意.DeclaredMethods 是类的一个属性。这正在按预期工作。

      你想要的代码(我认为)是

      var methodList = base.GetType().GetMethods();
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-25
      • 1970-01-01
      • 2011-06-27
      • 1970-01-01
      • 1970-01-01
      • 2015-01-10
      相关资源
      最近更新 更多