简体   繁体   中英

C# inheritance calling derived class functions from parent class

I have a class A which has become too long. So I have decided to move some of its functions to class B. I have made B inherit from A.

Now there are functions in A, which need functions in B. My question is where should I instantiate class B in class A. I cannot instantiate in the class A constructor, because class B will call the base class to create a never ending loop.

I only want class B to be instantiated once, because class A constructor has object which I only want to initialise once.

I am not even sure if I am making any sense now.

Inheritance is heavily overused. Especially in your case you want to prefer composition over inheritance .

The base keyword lets you access the superclass (baseclass): http://msdn.microsoft.com/en-us/library/hfw7t1ce(v=vs.71).aspx

BUT: If your only concern is the length of a class, it might be a better solution to use partial classes ( http://msdn.microsoft.com/en-us/library/wa80x488(v=vs.80).aspx ). You can split up your class into multiple files. Obviously what you are doing right now is not the intention and meaning of inheritance.

First of all its not best practice to define a new class when your class becomes too long. IF all functionality is logically related to the same object you can keep it in the same class no matter how long it is.

If you want B to be instantiated only once you should make it a static class. You can find more info about static classes in here: http://msdn.microsoft.com/en-us/library/79b3xss3(v=vs.80).aspx

If you make the functions abstract in A (this will have to make A abstract too), then just call those methods from A 's methods as you would normally. Then override the abstract functions in B with the logic you want. When the user instantiates the B class those calls will translate to calls in B even if the compile time type of the variable holding the instance is A .

You should only use inheritance if there is a true "is-a" relationship. To me, it sounds like you are describing functionality that class B needs. Perhaps B "has-a" A so you should consider composition instead of inheritance:

public class B
{
    private A a;

    public B(A a)
    {
       this.a = a;
    }

    public void UseAFunction()
    {
        a.MyFunction();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM