Mic*_*uso 4 c# inheritance interface interface-implementation
interface ITurtle
{
void Fight();
void EatPizza();
}
interface ILeonardo : ITurtle
{
void UseKatana();
}
interface IRaphael : ITurtle
{
void UseSai();
}
interface IDonatello : ITurtle
{
void UseBo();
}
interface IMichelangelo : ITurtle
{
void UseNunchuku();
}
Run Code Online (Sandbox Code Playgroud)
如果我想创建一个可以完成所有4个的大乌龟怎么办?我想编码:
class GrandTurtle : IMichelangelo, IDonatello, IRaphael, ILeonardo
{
// Implementation not shown for brevity.
}
Run Code Online (Sandbox Code Playgroud)
这是否可能,因为现在,似乎我必须实施Fight(),EatPizza()每次4次.但我认为这两个常用功能将解决,只需要实施一次,对吧?
我可以创建4个中间接口而不继承ITurtle,然后GrandTurtle实现ITurtle.这解决了接口继承问题,但现在它在语义上看起来是错误的,因为它ITurtle看起来像第5个兄弟,它不是.另外,我希望能够创建特定于龟的类,例如class BostonLeonardo : ILeonardo.
我从许多地方读过,似乎是一场无休止的争论 - 有人说"接口内的继承"很精细,那些说不是 - 我要么不理解他们的解释,要么他们只是说这是不好的做法而不解释为什么.
您只能实现这些方法Fight,EatPizza因为只有一个接口定义了它们.如果你有Fight和EatPizza每个ILeonardo等接口,你可以选择实现它们或使用显式接口实现来改变每个接口签名的那些方法的行为.我会做一个例子,因为我喜欢TMNT:
interface ILeonardo
{
void Fight();
void EatPizza();
void UseKatana();
}
interface IRaphael
{
void Fight();
void EatPizza();
void UseSai();
}
interface IDonatello
{
void Fight();
void EatPizza();
void UseBo();
}
interface IMichelangelo
{
void Fight();
void EatPizza();
void UseNunchuku();
}
class GrandTurtle : IMichelangelo, IDonatello, IRaphael, ILeonardo
{
// Code that fires when Fight is called on ILeonardo turtle = new GrandTurtle()
void ILeonardo.Fight()
{
UseKatana();
}
// Code that fires when Fight is called on IRaphael turtle = new GrandTurtle()
void IRaphael.Fight()
{
UseSai();
}
// Code that fires for all other turtles
public void Fight()
{
UseThatCrappyStickThingTheOldActionFiguresCameWith();
}
// Implement EatPizza() and such here...
}
Run Code Online (Sandbox Code Playgroud)
只有当GrandTurtle的类型签名是适当的接口时,这些显式接口实现才会生效.
编辑:对不起,我的回答最初是错的; 我一直在喝酒,TMNT让我兴奋
| 归档时间: |
|
| 查看次数: |
406 次 |
| 最近记录: |