方法隐藏在C#中使用有效的例子。为什么它在框架中实现?什么是真正的世界的优势在哪里? [英] method hiding in c# with a valid example. why is it implemented in the framework? what is the Real world advantage?
问题描述
任何人都可以解释在C#中的实际使用方式隐藏一个有效的例子吗?
Can anyone explain the actual use of method hiding in C# with a valid example ?
如果该方法是使用在派生类中新
关键字定义的,那么它不能被重写。然后,它是相同的创建新鲜方法(比基类中提到一个其它)用不同的名称。
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.
有没有使用新
关键字的具体原因是什么?
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屋!