【问题标题】:C# heritage : Call child method from parent method called by childC#遗产:从子调用的父方法调用子方法
【发布时间】:2014-11-20 12:38:43
【问题描述】:

我在这里遇到了一个问题,假设我有一个父类:

class ParentClass 
{
    public void MethodA()
    {
        //Do stuff
        MethodB();
    }

    public void MethodB()
    {
        //Do stuff
    }
}

继承 ParentClass 并覆盖 MethodB() 的子类:

class ChildClass : ParentClass
{
    public new void MethodB()
    {
        //Do stuff
    }
}

现在,如果我从 ChildClass 对象调用 MethodA()

public static void Main()
{
    ChildClass childObject = new ChildClass();
    childObject.MethodA();
}

我如何确定将调用的 MethodB() 帽子是来自子类的帽子?

【问题讨论】:

标签: c# inheritance


【解决方案1】:

如果你修复了编译错误,通过在父类中使方法virtual,并在子类中为方法添加返回值,那么它就可以正常工作了:

class ParentClass 
{
    …

    public virtual void MethodB()
    {
        //Do stuff
    }
}
class ChildClass : ParentClass
{
    public override void MethodB()
    {
        //Do stuff
    }
}

【讨论】:

  • 谢谢,我纠正了我在示例中犯的错误,因为我目前的情况是public new void MethodB()
【解决方案2】:
using System;

namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {
            var childObject = new ChildClass();

            childObject.MethodA();
            childObject.MethodB();
            childObject.MethodC();

            Console.ReadLine();
        }
    }

    class ParentClass 
    {
        public void MethodA()
        {
            //Do stuff
            _MethodB();
        }

        private void _MethodB()
        {
            Console.WriteLine("[B] I am called from parent.");
        }

        public virtual void MethodB()
        {
            _MethodB();
        }

        public void MethodC()
        {
            Console.WriteLine("[C] I am called from parent.");
        }
    }

    class ChildClass : ParentClass
    {
        public override void MethodB()
        {
            Console.WriteLine("[B] I am called from chield.");
        }

        public new void MethodC()
        {
            Console.WriteLine("[C] I am called from chield.");
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-14
    • 1970-01-01
    • 2017-06-26
    相关资源
    最近更新 更多