繁体   English   中英

派生的 class 如何覆盖 base 的 class 接口方法

[英]How does derived class override base's class interface method

我试图弄清楚方法覆盖在 C# 中是如何工作的,下一个代码和平真的让我感到困惑(.NET 5 和 C# 9.0):

    interface IPayable
    {
        public int Pay();
    }

    class Human : IPayable
    {
        int IPayable.Pay()
        {
            return 1;
        }
    }

    class Debtor : Human
    {
        int Pay()
        {
            return 0;
        }
    }

问题

Debtor.Pay()方法如何覆盖 base 的接口的 class 实现,而没有任何关于隐藏 base 的 class 功能的警告或在基本 class 方法中没有明确的virtual or abstract规范?

笔记

我知道如果我将Human.Pay()方法编写为virtual or abstract方法,我将能够显式地override它,但我的问题的重点是找出这段代码片段是如何隐式工作的。

好的,这是我不知道事物如何与接口和派生类一起工作。

我写了下一行:

            var human = new Human();
            var debtor = new Debtor();

            Console.WriteLine(((IPayable)human).Pay());
            Console.WriteLine(((IPayable)debtor).Pay());

           //Output: 1
           //        1

这意味着如果我显式实现IPayable.Pay()类的接口方法,则在派生的 class 中,粗略地说,将存在两个方法 - base.IPayable.Paythis.Pay 因此程序将其视为两种不同的方法,并且不会发出警告。

但是,如果我像这样更改一些代码:

    interface IPayable
    {
        public int Pay();
    }

    class Human : IPayable
    {
        public int Pay()
        {
            return 1;
        }
    }

    class Debtor : Human
    {
        int Pay()
        {
            return 0;
        }
    }

我会收到警告:

Warning CS0108 'Debtor.Pay()' hides inherited member 'Human.Pay()'. Use the new keyword if hiding was intended.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM