C# 为什么接口不能实现这样的方法?解决我的问题的解决方法是什么
本文关键字:方法 解决 我的 是什么 问题 接口 为什么 不能 实现 | 更新日期: 2023-09-27 18:33:33
为什么接口不能实现这样的方法?
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;
}
}
昆虫和僵尸都已经衍生自基础类生物,战斗机衍生自机器类 然而,并非所有生物都是可定位的,并且不使用 ITargetableUnit inteface。
是否有任何解决方法可以解决我面临的问题?
就像每个人都说的那样,你不能定义接口的行为。将接口继承给特定类。
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();
}
}
只是为了记录,你实际上可以这样做(DONT!),但这不被认为是为你可以访问的代码制作扩展方法的好做法。Mybirthname的解决方案是要走的路,这只是为了演示。
public interface ITargetableUnit { }
public static class ITargetableUnitExtension
{
public static bool unitCanBeTargeted(this ITargetableUnit unit)
{
bool targetable = false;
Insect insect = unit as Insect;
if(insect != null)
return insect.isFasterThanLight();
FighterJet jet = unit as FighterJet;
if(jet != null)
return !jet.Flying;
Zombie zombie = unit as Zombie;
if(zombie != null)
return zombie.Invisible;
return false;
}
}
也许你想要一个抽象类而不是一个接口?
接口定义类提供的方法。抽象类也可以做到这一点,但也可以为每个孩子接管一些计算。
请注意,从技术角度来看,Insect
也可以是Zombie
。
祝您编码愉快!
public abstract class TargetableUnit
{
//Returns whether the object of a class that implements this interface is targetable
public 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;
}
}
public class Insect : TargetableUnit
{
public bool isFasterThanLight()
{
return System.DateTime.UtcNow.Second == 0;
}
}
public class FighterJet : TargetableUnit
{
public bool Flying { get; set; }
}
public class Zombie : TargetableUnit
{
public bool Invisible { get; set; }
}