问题描述
当谈到执行,我应该如何决定去一个基本类型或接口?我试图几个例子锻炼,但我没有得到完整的思路:(
When it comes to implementation, how should i decide to go for an base type or an Interface ? I tried to work out on few examples but i don't get the complete idea :(
如何以及为什么会大大AP $ P $ .. pciated。
Examples on how and why would be greatly appreciated..
推荐答案
一个基类,抽象与否,可以包含执行委员。接口不能。如果你所有的实现都将执行同样,一个基类可能会去,因为所有的子类都可以在基类的共享成员相同的实现方式。如果他们不打算共享实现,那么接口可能是要走的路。
A base class, abstract or not, can contain implemented members. An interface cannot. If all of your implementations are going to perform similarly, a base class might be the way to go because all of your child classes can share the same implementations of the members on the base class. If they aren't going to share implementations, then an interface might be the way to go.
例如:
class Person
{
string Name { get; set; }
}
class Employee : Person
{
string Company { get; set; }
}
这是有道理的,员工从人继承,因为Employee类没有因为它的股票实施定义名称
属性。
interface IPolygon
{
double CalculateArea()
}
class Rectangle : IPolygon
{
double Width { get; set; }
double Height { get; set; }
double CalculateArea()
{
return this.Width * this.Height;
}
}
class Triangle : IPolygon
{
double Base { get; set; }
double Height { get; set; }
double CalculateArea()
{
return 0.5 * this.Base * this.Height;
}
}
由于长方形
和三角
有 CalculateArea $ C $的这种不同的实现C>,它没有意义为他们从基类继承。
Because Rectangle
and Triangle
have such differing implementations of CalculateArea
, it doesn't make sense for them to inherit from a base class.
如果你犯了一个基类,发现在的只有的包含抽象成员,你可能也只是使用接口。
If you make a base class, and find that in only contains abstract members, you may as well just use an interface.
和作为j__m状态,你不能从多个基类继承,但可以实现多个接口。
And, as j__m states, you cannot inherit from multiple base classes, but you can implement multiple interfaces.
我一般先定义接口,如果我发现自己复制code在我的实现,我创建一个实现该接口的基类,使我实现的继承它。
I usually define interfaces first, and if I find myself duplicating code in my implementations, I create a base class that implements the interface, and make my implementations inherit from it.
这篇关于如何为新的实现一个接口或基类之间做出选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!