首页 > c# > C#重新定义子类中的子方法,而无需在父类中重新定义调用方法

C#重新定义子类中的子方法,而无需在父类中重新定义调用方法 (C# redefine sub-method in child class without redefining calling method in parent class)

2019-02-28 c#inheritance

问题

我有一个包含许多方法的父类,它们都由一个顶级方法调用。

从概念上讲,父类看起来像这样:

class ParentClass
{
    void TopMethod(){ Lots of code and calls Methods1-N defined below}

    void Method1(){}
    void Method2(){}
    ...
    void MethodN(){}
}

我还有许多其他类,我想要只是这个基类的微小变化。所以我将它们声明为继承自ParentClass。说我需要做的就是改变Child Classes中Method1的定义。但是,我如何告诉子类使用ParentClass中的所有其他内容,只需使用Method1的新定义。特别是我不希望在子类中重写TopMethod的重复代码,所以我可以使它在子类中使用重新定义的Method1而不是ParentClass中的Method1。

解决方法

你需要做Method1Method2等虚拟和在子类覆盖它们。例如:

public class ParentClass
{
    public void TopMethod()
    {
        Console.WriteLine("Top method in parent");
        Method1();
    }

    public virtual void Method1()
    {
        Console.WriteLine("Method1 in parent");
    }
}

public class ChildClass : ParentClass
{
    public override void Method1()
    {
        Console.WriteLine("Method1 in child");
    }
}

现在调用每个类:

var parent = new ParentClass();
var child = new ChildClass();

parent.TopMethod();
child.TopMethod();

会给你这个输出:

Top method in parent
Method1 in parent
Top method in parent
Method1 in child

问题

I have a parent class with many methods in it that are all called by a single top-level method.

Conceptually the parent class looks like this:

class ParentClass
{
    void TopMethod(){ Lots of code and calls Methods1-N defined below}

    void Method1(){}
    void Method2(){}
    ...
    void MethodN(){}
}

I have many other classes that I want to be just minor variations on this base class. So I declare them as inheriting from ParentClass. Say all I need to do is change the definition of Method1 in the Child Classes. But how do I tell the child class to use everything else from the ParentClass, just with the new definition for Method1. In particular I don’t want the duplicate code of overriding TopMethod in the child class just so I can make it use the redefined Method1 in the child class instead of the Method1 in the ParentClass.

解决方法

You need to make Method1, Method2 etc. virtual and override them in the child class. For example:

public class ParentClass
{
    public void TopMethod()
    {
        Console.WriteLine("Top method in parent");
        Method1();
    }

    public virtual void Method1()
    {
        Console.WriteLine("Method1 in parent");
    }
}

public class ChildClass : ParentClass
{
    public override void Method1()
    {
        Console.WriteLine("Method1 in child");
    }
}

Now calling each class:

var parent = new ParentClass();
var child = new ChildClass();

parent.TopMethod();
child.TopMethod();

Will give you this output:

Top method in parent
Method1 in parent
Top method in parent
Method1 in child
相似信息