通过调用基类的方法打印派生类的方法名称

nob*_*ody 2 c# reflection inheritance abstract-class

我在c#中有以下课程,应该很容易理解

public abstract class BaseAbstract
{
    public void PrintMethodNames()
    {   // This line might needs change
        foreach (PropertyInfo pi in typeof(BaseAbstract).GetProperties())
        {
            Console.WriteLine(pi.Name);
        }
    }
}

public class DerivedClass : BaseAbstract
{
    public void MethodA() { }
    public void MethodB() { }
    public void MethodC() { }
}

public class MainClass
{
    public static void Main()
    {
        BaseAbstract ba = new DerivedClass();
        ba.PrintMethodNames();
        // desired printout 
        // MethodA
        // MethodB
        // MethodC
        // but obviously not working
    }
}
Run Code Online (Sandbox Code Playgroud)

那我在找什么?

Chr*_*ich 6

这里有一些问题:

  1. MethodA,MethodB和,MethodC是方法,而不是属性,所以你需要使用GetMethods而不是GetProperties.
  2. 您应该使用当前实例类型(GetType)而不是基类类型(typeof(BaseAbstract)).
  3. 您需要使用约束反射BindingFlags才能获得派生类上定义的方法.否则,如果没有这些标志,您将获得在类型上定义的所有方法(例如ToString,GetHashCode甚至PrintMethodNames).

这打印出您的期望:

public abstract class BaseAbstract
{
    public void PrintMethodNames()
    {
        BindingFlags flags =
            BindingFlags.DeclaredOnly |
            BindingFlags.Public |
            BindingFlags.Instance |
            BindingFlags.Static;

        foreach (MethodInfo mi in GetType().GetMethods(flags))
        {
            Console.WriteLine(mi.Name);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)