【问题标题】:Printout the method name of a derived class by calling method of a base class通过调用基类的方法打印出派生类的方法名
【发布时间】:2011-04-05 21:38:52
【问题描述】:

我在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
    }
}

那么我在寻找什么?

【问题讨论】:

    标签: c# reflection inheritance abstract-class


    【解决方案1】:

    这里有几个问题:

    1. MethodAMethodBMethodC 是方法,而不是属性,因此您需要使用 GetMethods 而不是 GetProperties
    2. 您应该使用当前实例类型 (GetType) 而不是基类的类型 (typeof(BaseAbstract))。
    3. 您需要使用BindingFlags 来约束反射,以便仅获取派生类上定义的方法。否则,如果没有这些标志,您将获得在该类型上定义的所有方法(如 ToStringGetHashCode 甚至 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);
            }
        }
    }
    

    【讨论】:

    • 问题是他想列出 BaseClass 中的所有 DerivedCalss 方法(相反)。基类不知道它是派生类,这就是问题所在。
    • @HABJAN:我提供的代码就是这样做的。如果你将他的BaseAbstract 换成我上面的版本并运行程序,你会看到它打印出所需的输出(只是DerivedClass 中定义的方法)。
    • @HABJAN:参见第 2 点:GetType 返回实例的运行时类型,而不是调用 GetType 的静态类型。因此,在这种特定情况下,GetType 返回DerivedClass
    【解决方案2】:

    typeof(BaseAbstract).GetProperties() 替换为this.GetType().GetProperties()

    【讨论】:

    • 感谢您的快速回复,但我将把答案归功于 Chris Schmich 添加 BindingFlag 代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    • 2015-04-08
    • 1970-01-01
    • 2021-11-01
    • 2021-07-18
    • 2014-03-17
    • 2014-09-05
    相关资源
    最近更新 更多