【发布时间】:2016-02-06 17:22:02
【问题描述】:
为什么接口不能实现这样的方法?
public interface ITargetableUnit {
//Returns whether the object of a class that implements this interface is targetable
bool unitCanBeTargeted(){
bool targetable = false;
if(this is Insect){
targetable = (this as Insect).isFasterThanLight();
}
else if(this is FighterJet){
targetable = !(this as FighterJet).Flying;
}
else if(this is Zombie){
targetable = !(this as Zombie).Invisible;
}
return targetable;
}
}
Insect 和 Zombie 都已经派生自基类 Creature,而 FighterJet 派生自类 Machine 但是,并非所有 Creature-s 都是可定位的并且不使用 ITargetableUnit 接口。
是否有任何解决方法可以解决我面临的问题?
【问题讨论】:
-
接口没有行为,你要找的是抽象类
-
因为接口不允许你提供实现。而是创建这样的层次结构,
Creature->TargetableCreature->Insect/Ghost/Zombie和Creature->NonTargetableCreature->WhateverIsntTargetable但是,因为您的界面有不同的每种类型的实现,你应该只在每个类中实现接口。 -
你应该有一个
ITargetableCreature和INonTargetableCreature然后在 main 方法中检查其中任何一个。
标签: c# interface implementation