用作声明修饰符时, new
关键字显式隐藏从基类继承的成员。 隐藏继承成员时,该成员的派生版本将替换基类版本。 这假定成员的基类版本可见,因为它已被标记为 private
或在某些情况下 internal
已被隐藏。 虽然可以在不使用修饰符的情况下new
隐藏public
或protected
成员,但会收到编译器警告。 如果使用 new
显式隐藏成员,它将禁止显示此警告。
还可以使用 new
关键字 创建类型实例 或泛 型类型约束。
若要隐藏继承的成员,请使用同一成员名称在派生类中声明该成员,并使用关键字对其进行修改 new
。 例如:
public class BaseC
{
public int x;
public void Invoke() { }
}
public class DerivedC : BaseC
{
new public void Invoke() { }
}
在此示例中,BaseC.Invoke
隐藏者。DerivedC.Invoke
该字段不受影响,因为该字段 x
未由类似名称隐藏。
通过继承隐藏的名称采用以下形式之一:
通常,类或结构中引入的常量、字段、属性或类型隐藏共享其名称的所有基类成员。 有特殊情况。 例如,如果声明一个名称
N
为不可调用的类型的新字段,而基类型声明N
为方法,则新字段不会在调用语法中隐藏基本声明。 有关详细信息,请参阅 C# 语言规范的成员查找部分。类或结构中引入的方法隐藏在基类中共享该名称的属性、字段和类型。 它还隐藏具有相同签名的所有基类方法。
类或结构中引入的索引器隐藏具有相同签名的所有基类索引器。
对同一成员使用 new
和 重写 是错误的,因为两个修饰符具有互斥的含义。 修饰 new
符创建具有相同名称的新成员,并导致原始成员隐藏。 修饰 override
符扩展继承成员的实现。
在 new
不隐藏继承成员的声明中使用修饰符将生成警告。
例子
在此示例中,基类 BaseC
和派生类 DerivedC
使用相同的字段名称,该名称 x
隐藏继承字段的值。 该示例演示了修饰符的使用 new
。 它还演示如何使用基类的完全限定名称访问隐藏成员。
public class BaseC
{
public static int x = 55;
public static int y = 22;
}
public class DerivedC : BaseC
{
// Hide field 'x'.
new public static int x = 100;
static void Main()
{
// Display the new value of x:
Console.WriteLine(x);
// Display the hidden value of x:
Console.WriteLine(BaseC.x);
// Display the unhidden member y:
Console.WriteLine(y);
}
}
/*
Output:
100
55
22
*/
在此示例中,嵌套类隐藏在基类中具有相同名称的类。 该示例演示如何使用 new
修饰符来消除警告消息,以及如何使用其完全限定的名称访问隐藏类成员。
public class BaseC
{
public class NestedC
{
public int x = 200;
public int y;
}
}
public class DerivedC : BaseC
{
// Nested type hiding the base type members.
new public class NestedC
{
public int x = 100;
public int y;
public int z;
}
static void Main()
{
// Creating an object from the overlapping class:
NestedC c1 = new NestedC();
// Creating an object from the hidden class:
BaseC.NestedC c2 = new BaseC.NestedC();
Console.WriteLine(c1.x);
Console.WriteLine(c2.x);
}
}
/*
Output:
100
200
*/
如果删除 new
修饰符,程序仍将编译并运行,但会收到以下警告:
The keyword new is required on 'MyDerivedC.x' because it hides inherited member 'MyBaseC.x'.