【发布时间】:2018-07-19 08:27:30
【问题描述】:
尊敬的 OOP 专家您好,
如果之前有人问过这个问题,我很抱歉,我还没有找到任何类似的问题(我可能没有合适的词来解释)。
为了制作一个灵活的系统,我尝试使用Interfaces 和Abstract 类。涉及的实体非常简单:
public interface IAbilityTarget
{
// A bunch of properties and functions
}
public interface IDamagable : IAbilityTarget
{
int Life { get; set; }
}
public abstract class Ability
{
public abstract bool CanBeUsed( IAbilityTarget[] targets );
public abstract void Use( IAbilityTarget[] targets );
}
public class Fireball : Ability
{
public override bool CanBeUsed( IDamagable[] targets )
{
return true ; // for the sake of the example
}
public override void Use( IDamagable[] targets )
{
for( int index = 0 ; index < targets.Length ; ++index )
targets[index].Life -= 1 ;
}
}
我的问题如下:为什么我有CS0115 错误?
错误 CS0115:`Fireball.CanBeUsed(IDamagable[])' 被标记为覆盖,但找不到合适的覆盖方法
由于IDamagable 扩展了IAbilityTarget,我不明白为什么会出现错误。我不想在Fireball 中实现以下内容以避免错误:
public override bool CanBeUsed( IAbilityTarget[] targets )
{
return true;
}
public bool CanBeUsed( IDamagable[] targets )
{
return CanBeUsed( (IAbilityTarget[]) targets );
}
为了避免错误,我必须进行哪些更改,而不必为每个子接口重载CanBeUsed。
【问题讨论】:
-
IDamagable 比 IAbilityTarget 更专业。在抽象类中指定 IAbilityTarget 意味着实现者只能确定 IAbilityTarget 的成员是否存在。
标签: c# oop inheritance interface