关于在基类和派生类中实现接口的问题 [英] Question about implementing interfaces in a base class and derived class

查看:99
本文介绍了关于在基类和派生类中实现接口的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了游泳,嘎嘎和苍蝇的输出。我不知道如何从派生类Mallard,RubberDuck和DecoyDuck获取输出。从基类实现派生类时,我做错了吗?任何人都可以帮助我。



I am getting output as swim, quack and fly. I don't know how to get output from my derived class Mallard, RubberDuck and DecoyDuck. Am I doing anything wrong while implementing derived class from my base class? Can anyone help me.

{
    interface IFlyBehavior
    {
        void Action1();
    }
    interface IQuackBehavior:IFlyBehavior
    {
        void Action2();
    }
    interface ISwimBehavior:IQuackBehavior
    {
        void Action3();
    }
    public class Duck:IQuackBehavior
    {
        public void Action1()
        {
           Console.WriteLine("fly");
        }
        public void Action2()
        {
            Console.WriteLine("quack");
        }
        public void Action3()
        {
            Console.WriteLine("Swim");
        }
    }
    public class Mallard: Duck, IFlyBehavior, IQuackBehavior, ISwimBehavior
    {
       public void Action1(string fly, string quack, string swim){
        Console.WriteLine("This duck can {0}, {1}, and {2}", fly, quack, swim);}
    }
    public class RubberDuck: Duck, IFlyBehavior, IQuackBehavior, ISwimBehavior
    {
         public void Action2(string fly, string quack, string swim)
         {
       Console.WriteLine ("This is rubberduck so it might float on water but cannot {0}, {1} or {2}",fly,quack,swim);
       }
    }
    public class DecoyDuck: Duck, IFlyBehavior, IQuackBehavior, ISwimBehavior
    {
         public void Action3(string fly, string swim, string quack) {
        Console.WriteLine("This duck cannot {0}, but {1}, and may be able to {2}",fly,swim,quack);}
    }
    class Program
    {
        static void Main()
        {
            Duck M = new Mallard();
            Duck R = new RubberDuck();
            Duck D = new DecoyDuck();
            M.Action1();
            R.Action2();
            D.Action3();


        }
    }
}

推荐答案

您的代码已包含一些问题:如果要覆盖派生类中的方法,则应该在基类中使用 virtual 关键字( public virtual void Action1 ),派生类中的覆盖关键字( public override void Action1 ) 。

但请注意:对于基本方法和派生方法,函数签名(即返回类型和参数类型)必须相同。
Your code has a few problems: if you want to override a method in a derived class, you ought to use the virtual keyword in the base class (public virtual void Action1), and the override keyword in the derived class (public override void Action1).
But note: the function signature (i.e. return type and parameter types) must be the same for base and derived methods.


这篇关于关于在基类和派生类中实现接口的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆