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

时间:2012-03-01 06:52:28

标签: c# methods new-operator

-new-关键字在这里意味着什么?

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

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

3 个答案:

答案 0 :(得分:6)

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"

答案 1 :(得分:1)

new关键字。如果在方法上使用它,则隐藏现有的继承方法。

在您的情况下,由于X不是从任何类派生的,因此您会收到警告,指出new关键字不会隐藏任何现有方法。

此方法也是私有的(默认情况下),无法在课外访问。

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

答案 2 :(得分:1)

相关问题