method hiding in c# with a valid example. why is it implemented in the framework? what is the Real world advantage?(隐藏在 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# 中的方法和一个有效的例子.为什么要在框架中实现?现实世界的优势是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:隐藏在 c# 中的方法和一个有效的例子.为什么要在框架中实现?现实世界的优势是什么?
基础教程推荐
- Moq It.Is<>不匹配 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- WPF 模态进度窗口 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
