隐藏在 c# 中的方法和一个有效的例子.为什么要在框架中实现?现实世界的优势是什么? [英] method hiding in c# with a valid example. why is it implemented in the framework? what is the Real world advantage?

查看:17
本文介绍了隐藏在 c# 中的方法和一个有效的例子.为什么要在框架中实现?现实世界的优势是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能用一个有效的例子来解释方法隐藏在C#中的实际使用?

Can anyone explain the actual use of method hiding in C# with a valid example ?

如果方法是在派生类中使用 new 关键字定义的,则它不能被覆盖.然后它与创建一个具有不同名称的新方法(基类中提到的方法除外)相同.

If the method is defined using the new keyword in the derived class, then it cannot be overridden. Then it is the same as creating a fresh method (other than the one mentioned in the base class) with a different name.

使用 new 关键字有什么特别的原因吗?

Is there any specific reason to use the new keyword?

推荐答案

C#不仅支持方法覆盖,还支持方法隐藏.简单地说,如果一个方法没有覆盖派生方法,它就是隐藏它.必须使用 new 关键字声明隐藏方法.因此,第二个清单中正确的类定义是:

C# not only supports method overriding, but also method hiding. Simply put, if a method is not overriding the derived method, it is hiding it. A hiding method has to be declared using the new keyword. The correct class definition in the second listing is thus:

    using System;
    namespace Polymorphism
    {
        class A
        {
            public void Foo() { Console.WriteLine("A::Foo()"); }
        }

        class B : A
        {
            public new void Foo() { Console.WriteLine("B::Foo()"); }
        }

        class Test
        {
            static void Main(string[] args)
            {
                A a;
                B b;

                a = new A();
                b = new B();
                a.Foo();  // output --> "A::Foo()"
                b.Foo();  // output --> "B::Foo()"

                a = new B();
                a.Foo();  // output --> "A::Foo()"
            }
        }
    }

这篇关于隐藏在 c# 中的方法和一个有效的例子.为什么要在框架中实现?现实世界的优势是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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