隐藏/隐藏方法 [英] Hiding /Shadowing of the methods

查看:85
本文介绍了隐藏/隐藏方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Program
    {
        static void Main(string[] args)
        {
            IInterface interfaceFromBase = new Base();

            Console.WriteLine(interfaceFromBase.test());

            Console.WriteLine(interfaceFromBase.test1());



            IInterface interfaceFromDerived = new Derived();

            Console.WriteLine(interfaceFromDerived.test());

            Console.WriteLine(interfaceFromDerived.test1());



            Console.ReadLine();
        }
    }

    interface IInterface
    {

        string test();

        string test1();

    }



    class Base : IInterface
    {

        public string test()
        {

            return "Test: I'm in Base";

        }



        public string test1()
        {

            return "Test1: I'm in Base";

        }

    }

    class Derived : Base ,IInterface
    {

        public new string test()
        {

            return "Test: I'm in Derived";

        }

    }



上面函数的输出是
测试:我在基地
Test1:我在基地
测试:我在派生
Test1:我在基地

如果仅从Base派生Derived类,则输出将为
测试:我在基地
Test1:我在基地
测试:我在基地
Test1:我在基地



The output of the above function is
Test: I''m in Base
Test1: I''m in Base
Test: I''m in Derived
Test1: I''m in Base

If the Derived class is to be derived from Base only then the output would be
Test: I''m in Base
Test1: I''m in Base
Test: I''m in Base
Test1: I''m in Base

Would anyone please give me the difference?

推荐答案

您遇到的是newoverride之间的区别.顺便说一句:后者要求将基类方法声明为virtual.

建议您阅读所有这些关键字.

:)
you are experiencing the difference between new and override. BTW: The latter requires the base class method to be declared virtual.

I suggest you read up on all these keywords.

:)


这篇关于隐藏/隐藏方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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