关键字-new-在方法实现之前

本文关键字:实现 方法 -new- 关键字 | 更新日期: 2023-09-27 18:26:28

这里的-new关键字是什么意思?

  class X
  {
        new byte Method ()
        {
              return 5;
        }
  }

我在stackoverflow上找到了一些,但我需要尽可能简单的答案(糟糕的英语)。

关键字-new-在方法实现之前

new对基类隐藏方法:

class Base
{ 
    byte Method () 
    { 
          return 4; 
    } 
} 
class X : Base
{ 
    new byte Method () 
    { 
          return 5; 
    } 
} 
X x = new X();
Base b = x;
Console.WriteLine(x.Method()); // Prints "5"
Console.WriteLine(b.Method()); // Prints "4"

值得注意的是,如果方法是虚拟的,并且您使用override而不是new,则行为是不同的:

class Base
{ 
    virtual byte Method () 
    { 
          return 4; 
    } 
} 
class X : Base
{ 
    override byte Method () 
    { 
          return 5; 
    } 
} 
X x = new X();
Base b = x;
Console.WriteLine(x.Method()); // Prints "5"
Console.WriteLine(b.Method()); // Prints "5"

也可以参阅此主题:http://msdn.microsoft.com/en-us/library/6fawty39(v=vs.80).aspx

这是新的关键字。如果在方法上使用,它将隐藏现有的继承方法。

在您的情况下,由于X不是从任何类派生的,您将收到一条警告,说明new关键字不会隐藏任何现有方法。

此外,该方法是私有的(默认情况下),不能在类之外访问。

如果X确实派生自具有该方法的类,它将隐藏它。@phoog在他的回答中有很好的例子。