战斗机类没有实现接口成员

时间:2015-06-17 13:37:37

标签: c# class interface

我收到了这个错误:

  

错误1'Fight.Fighter'未实现接口成员   'Fight.IFighter.Utok(Fight.IFighter)'

这是我第一次尝试学习界面,很抱歉转储问题。

有什么想法吗?

我有以下代码:

接口:

    interface IFighter
    {
        string GraphicLife();
        bool IsLive();
        int Obrana(int utocneCislo);
        void Utok(IFighter bojovnik);
    }
}

类别:

class Fighter : IFighter
{
    protected string name;
    protected int life;
    protected int maxLife;
    protected int attack;
    protected int defence;

    protected Kostka kostka;

    public Fighter(string name, int life, int maxLife, int attack, int defence, Kostka kostka){
        this.name = name;
        this.life = life;
        this.maxLife = maxLife;
        this.attack = attack;
        this.defence = defence;
        this.kostka = kostka;
    }

    public bool IsLive()
    {
        if (life > 0)
        {
            return true;
        }
        else return false;
    }

    public string GraphicLife()
    {
        int pozic = 20;
        int numberOfParts = (int)Math.Round(((double)life / (double)maxLife) * (double)pozic);
        string zivot = String.Concat(Enumerable.Repeat("#", numberOfParts));
        zivot = zivot + String.Concat(Enumerable.Repeat("_", pozic - numberOfParts));
        zivot = "[" + zivot + "]";
        return zivot;
    }

    public void Utok(Fighter warrior)
    {
        if (warrior.IsLive())
        {
            int utok = (int)Math.Round((double)attack / (double)kostka.getPocetStran() * (double)kostka.getNumber());
            int obrana = warrior.Obrana(utok);
            Console.WriteLine(this.name + "utoci na " + warrior.name + " silou " + utok + " " + warrior.name + " se brani silou " + obrana);
            Console.WriteLine(this.name + " - " + this.life);
            Console.WriteLine(this.GraphicLife());
            Console.WriteLine(warrior.name + " - " + warrior.life);
            Console.WriteLine(warrior.GraphicLife());
        }
        else Console.WriteLine(this.name + " utoci na mrtvolu");
    }

    public int Obrana(int attackNumber)
    {
        int localDefence = (int)Math.Round((double)defence/ (double)kostka.getPocetStran() * (double)kostka.getNumber());
        int utok = attackNumber - localDefence;
        if (utok < 0) utok = 0;
        life = life - utok;
        return localDefence;
    }

}}

2 个答案:

答案 0 :(得分:4)

您在方法的参数列表中使用具体类型 Fighter 而不是抽象类型 IFighter

更改以下行

public void Utok(Fighter warrior)

public void Utok(IFighter warrior)

如果在类中实现,则需要使用界面中定义的确切类型

如果在创建类之前定义接口(这是最常用的方法),可以使用Visual Studio提供的一个很好的帮助程序为您完成一些工作。将光标指向interface-name并使用&#34;实现接口&#34; -function为您的接口自动创建方法存根。

编辑:

您需要添加属性&#34; Name&#34;到界面以使其工作。它必须是至少需要吸气剂的财产:

string name { get; }

普通变量而不是getter在这里不起作用,因为接口不能包含变量。

只有接口的属性可用,无论在应用程序的其他位置实际实现该接口的类数。

答案 1 :(得分:2)

Utok的方法签名需要IFighter的实例,而不是您的接口合同定义的Fighter

public void Utok(IFighter warrior)
{
    // ...
}
  

要实现接口成员,实现类的相应成员必须是公共的,非静态的,并且具有相同的名称,并且签名作为接口成员。

这意味着完全相同的签名

相关问题