综合编程

Inheritance extensions?

微信扫一扫,分享到朋友圈

Inheritance extensions?
0

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();

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;} }
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.

阅读原文...

微信扫一扫,分享到朋友圈

Inheritance extensions?
0
Hello, buddy!

ApexSQL Unit Test 2018 R3 – Product update alert

上一篇

openrsync imported into OpenBSD tree

下一篇

评论已经被关闭。

插入图片

热门分类

往期推荐

Inheritance extensions?

长按储存图像,分享给朋友