为什么接口不能实现这样的方法?C#为什么接口不能实现这样的方法?什么是解决我的问题的解决方法?
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;
}
}
昆虫,和僵尸都已经从基类派生生物和FighterJet从类机派生然而,并非所有的生物-S是靶向,不使用ITargetableUnit inteface。
有没有解决我面临的问题的解决方法?
接口没有行为,你要找的是抽象类 – Uriil
因为接口不允许你提供实现。取而代之的是像这样的结构,'Creature' - >'TargetableCreature' - >'Insect' /'Ghost' /'Zombie'和'Creature' - >'NonTargetableCreature' - >'WhateverIsntTargetable'然而,因为你的界面有不同的每种类型的实现,你应该在每个类中实现接口。 – dman2306
你应该只需要一个'ITargetableCreature'和'INonTargetableCreature',然后检查主要方法中的任何一个。 –