简体   繁体   中英

How does derived class override base's class interface method

I'm trying to figure out how does method overriding works in C# and next peace of code really confuced me (.NET 5 and C# 9.0):

    interface IPayable
    {
        public int Pay();
    }

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

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

Question

How does Debtor.Pay() method override base's class implementation of interface without any warning about hiding base's class functionality or without explicit virtual or abstract specification in base class method?

Note

I know that if I write Human.Pay() method as virtual or abstract I will be able to override it explicitly, but the main point of my question is to find out how this code snippet implicitly works.

OK, it was my unawareness about how thing works with interfaces and derived classes.

I wrote next lines:

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

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

           //Output: 1
           //        1

That means that if I explicitly implements interfaces method like this IPayable.Pay() , inside derived class, roughly speaking, will exist two methods - base.IPayable.Pay and this.Pay . Thus program considers it like two different methods and doesn't warn about it.

But if I change a little code like this:

    interface IPayable
    {
        public int Pay();
    }

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

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

I'll get a warning:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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