简体   繁体   中英

extensions of inheritance?

I have a class:

class A {
    method 1
    method 2
    method 3
}

now I would like to add a new method: method 4, nut I cannot modify class A file. What is the best practice:
1. Should I use extensions?
2. Should I inherit A and there I'll implement the new method? If so - what will be the name of the child class?

Later on I would like to be able to do:

A ains=new A(); //A or other name
ains.method4();

The rule I usually go by in this scenario is

Am I adding just a behavior or data and / or behavior?

If I'm just adding a behavior to an existing type but not any new data then I add an extension method. It's the least intrusive way of getting the behavior and removes the need for deep object hierarchies.

If there is a piece of data I need to add along with that behavior then I will consider inheritance or wrapping in yet another type.

Sounds like you need to use an extension, but without more information it is hard to tell. Inheritance is when the child is a type of A , not when you just need to add a method.

Depends on the usage scenario. A does not have Method4, so no method that accepts an A as it's parameter can rely on Method4 being existent.

If you only need Method4 as a Helper internal to your class, implement it as an extension. Otherwise create a class B that derives from A so that external classes that need Method4 can reliably request a B as their parameter instead of an A .

Of course, Exceptions always apply. LINQ is an example of where subclassing would be impractical.

In a comment you mentioned the need for a property. In this case, creating a class B : A is your main option as there are no Extension Properties. The other option is creating a class B { public A TheA {get; set;} } class B { public A TheA {get; set;} } which wraps around A.

But as said, it depends on the real world case and usage. If you absolutely must work with an A and need to call methods on this A , then extension methods are your choice and you can't have properties. Instead, create Get/Set methods and store the property value somewhere else.

Use inheritance only when you will be able to use the reference of A wherever you want to use the reference of the derived class. If your sole intention is to make use of the methods in A, use delegation.

On the other hand, you could try extensions though.

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