有关C#中的新修饰符的帮助 [英] Help regarding new modifier in C#
本文介绍了有关C#中的新修饰符的帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Hi,
public class ClassA
{
public void MethodNew()
{
Console.WriteLine("In MethodNew of ClassA");
}
public virtual void MethodOverride()
{
Console.WriteLine("In MethodOverride of ClassA");
}
}
public class ClassB : ClassA
{
public new void MethodNew()
{
Console.WriteLine("In MethodNew of ClassB");
}
public override void MethodOverride()
{
Console.WriteLine("In MethodOverride of ClassB");
}
}
class Program
{
static void Main(string[] args)
{
ClassA a = new ClassB();
a.MethodNew();
a.MethodOverride();
}
}
在上面的示例中,尽管我在派生类中为Methodnew函数添加了不添加新关键字,但o/p始终在基类中调用方法...
那么在这里使用new的目的是什么?
In the above sample eventhough I append or not new keyword for Methodnew function in the derived class,the o/p is always calling method in base class...
So what is the purpose of using new here?
推荐答案
这是正确的行为,因为:
- 您正在使用多态性创建
ClassB
实例.- 基类"
MethodNew
不是virtual
.
That''s the correct behaviour, since:
- You''re using polymorphism to create
ClassB
instance.- Base class''
MethodNew
is NOTvirtual
.
我的问题是关于修饰符new
的,就像在公共new void MethodNew()
中一样,而不是用于初始化的运算符new
.修饰符new
是完全不同的东西,它用于隐藏成员时消除编译器警告.
请考虑以下内容:
I thing the question is about modifiernew
as in publicnew void MethodNew()
, not operatornew
used for initialization. The modifiernew
is absolutely different thing, it''s used to dismiss compiler warning when hiding a member.
Consider the following:
class Base {
protected void Visible() { }
} //class Base
class AccedentallyHiding : Base {
//will shows warning: Visible() hides inherited member
//Base.Visible(). Use the new keyword if hiding is intended
protected void Visible() { }
} //class AccedentallyHiding
class IntentionallyHiding : Base {
//no problem: keyword "new" shows intended hiding
protected new void Visible() { }
} //class IntentionallyHiding
请参阅解释编译器行为的代码注释.
Please see code comments explaining compiler behavior.
这篇关于有关C#中的新修饰符的帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文