为什么接口不能实现这样的方法?
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;
}
}
Run Code Online (Sandbox Code Playgroud)
Insect和Zombie都已经从基类Creature派生而来,而FighterJet派生自类Machine但是,并非所有的Creature都是可定位的,并且不使用ITargetableUnit inteface.
是否有任何解决方法可以解决我所面临的问题?
我的Python程序使用字典,并且有大量的“if”语句只是为了检查检索到的值的类型。
我想避免这种情况,而是以更编程正确的方式进行。
这是一个例子:
# golddb should only contain str keys and int values
golddb = dict()
def gainGold(playername):
global golddb
golddb[playername] += 1 # error may happen if I try to += a non-int type
golddb[playername] = "hello" # I want python to give an error when I try to assign a str to be a value in the dict
Run Code Online (Sandbox Code Playgroud)