Using the #39;new#39; modifier in C#(在 C# 中使用“新修饰符)
问题描述
我读到 new
修饰符隐藏了基类方法.
I read that the new
modifer hides the base class method.
using System;
class A
{
public void Y()
{
Console.WriteLine("A.Y");
}
}
class B : A
{
public new void Y()
{
// This method HIDES A.Y.
// It is only called through the B type reference.
Console.WriteLine("B.Y");
}
}
class Program
{
static void Main()
{
A ref1 = new A(); // Different new
A ref2 = new B(); // Polymorpishm
B ref3 = new B();
ref1.Y();
ref2.Y(); //Produces A.Y line #xx
ref3.Y();
}
}
为什么 ref2.Y();
产生 A.Y
作为输出?
Why does ref2.Y();
produce A.Y
as output?
这是简单的多态,基类对象指向派生类,所以应该调用派生类函数.我实际上是 Java 兼 C# 编码器;这些概念让我大吃一惊.
This is simple polymorphism, the base class object pointing towards derived class, so it should call the derived class function. I am actually Java cum C# coder; these concepts just boggled my mind.
当我们说new
隐藏基类函数时,就是说base类函数不能被调用,这就是隐藏的意思据我所知.
When we say new
hides the base class function, that means the base class function can't be called, that's what hides mean as far as I know.
参考
推荐答案
在 C# 中,方法默认不是虚拟的(与 Java 不同).因此,ref2.Y()
方法调用不是多态的.
In C#, methods are not virtual by default (unlike Java). Therefore, ref2.Y()
method call is not polymorphic.
要从多态中受益,您应该将 AY()
方法标记为 virtual
,并将 BY()
方法标记为 override
.
To benefit from the polymorphism, you should mark A.Y()
method as virtual
, and B.Y()
method as override
.
new
修饰符所做的只是隐藏从基类继承的成员.这就是您的 Main()
方法中真正发生的事情:
What new
modifier does is simply hiding a member that is inherited from a base class. That's what really happens in your Main()
method:
A ref1 = new A();
A ref2 = new B();
B ref3 = new B();
ref1.Y(); // A.Y
ref2.Y(); // A.Y - hidden method called, no polymorphism
ref3.Y(); // B.Y - new method called
这篇关于在 C# 中使用“新"修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C# 中使用“新"修饰符


- C# 中多线程网络服务器的模式 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01