C#为什么接口不能实现这样的方法?解决我的问题的解决方法是什么?

Rya*_* WE 0 c# implementation interface

为什么接口不能实现这样的方法?

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.

是否有任何解决方法可以解决我所面临的问题?

myb*_*ame 7

就像每个人都说你无法定义接口的行为.继承特定类的接口.

public interface ITargetableUnit 
{

     bool unitCanBeTargeted();

}

public class Insect : ITargetableUnit //you can add other interfaces here
{

     public bool unitCanBeTarget()
     {
          return isFasterThanLight();
     }
}

public class Ghost : ITargetableUnit 
{
     public bool unitCanBeTarget()
     {
          return !Flying();
     }
}

public class Zombie : ItargetableUnit
{
     public bool unitCanBeTarget()
     {
          return !Invisible();
     }
}
Run Code Online (Sandbox Code Playgroud)