我有两个类(class)
class A
{
public virtual void Metod1()
{
Console.WriteLine("A.Method1");
}
}
class B : A
{
public new void Metod1()
{
Console.WriteLine("B.Method1");
}
}
然后我写一些代码来声明这些类的实例,并调用它们的方法
static void Main(string[] args)
{
A a = new B();
a.Metod1();
B b = new B();
b.Metod1();
Console.ReadKey();
}
我给出了以下结果:
A.Method1
B.Method1
但是当我从类 B 的签名方法 1 中删除关键字 new 并运行 Main 方法时,我得到了相同的结果。
问题:方法签名中的新关键字是否只是为了更好的可读性?
编辑:是否存在我们不能没有新关键字的情况?
new 关键字让代码阅读者知道此方法将隐藏其基类中具有相同名称的方法。即使您忽略了它,编译器也会以同样的方式对待它,但会警告您。
由于您将该方法声明为virtual,因此您在编译时会收到此警告:
'B.Metod1()' hides inherited member 'A.Metod1()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.
但是,如果您通过删除 virtual 来更改声明:
仍会编译,但警告消息将是:
'B.Metod1()' hides inherited member 'A.Metod1()'. Use the new keyword if hiding was intended.
以上述任一方式,如下:
将输出:
B.Method1
A.Method1
But, if you declare as the following:
那么输出将是:
B.Method1
B.Method1
That is because Method1
of the base class is not just hidden but overridden by the derived class.
A case that you cannot just use new is that if Method1
is a abstract method in a abstract class:
Code that must use override in derived classes
abstract class A {
public abstract void Metod1();
}
class B: A {
public override void Metod1() { // use `new` instead of `override` would not compile
Console.WriteLine("B.Method1");
}
}
在这种情况下,您不能只使用 new,因为 A
需要派生类来覆盖 Method1
。