original article
标签: C# 编程语言
C# override and new keywords
override 标识符用于扩展基类方法,而 new 标识符用于隐藏基类方法。
比如对于如下两个类:base class 和 derived class
class BaseClass
{
public void Method1()
{
Console.WriteLine("Base - Method1");
}
}
class DerivedClass : BaseClass
{
public void Method2()
{
Console.WriteLine("Derived - Method2");
}
}
有三个对象bc,dc和bcdc。
其中bc的类型是基类,有着基类的数据;dc的类型是派生类,有着派生类的数据;bcdc的类型是基类,但它有着派生类的数据。
如果不使用override标识符直接重写函数,效果等同于加了new标识符,不过编译器会发出警告。
Main
class Program
{
static void Main(string[] args)
{
BaseClass bc = new BaseClass();
DerivedClass dc = new DerivedClass();
BaseClass bcdc = new DerivedClass();
bc.Method1();
dc.Method1();
dc.Method2();
bcdc.Method1();
}
// Output:
// Base - Method1
// Base - Method1
// Derived - Method2
// Base - Method1
}
加上基类的Method2后
public void Method2()
{
Console.WriteLine("Base - Method2");
}
bc.Method1();
bc.Method2();
dc.Method1();
dc.Method2();
bcdc.Method1();
bcdc.Method2();
// Output:
// Base - Method1
// Base - Method2
// Base - Method1
// Derived - Method2
// Base - Method1
// Base - Method2
而如果使用override来重写方法一,结果会不同。
public override void Method1()
{
Console.WriteLine("Derived - Method1");
}
// Output:
// Base - Method1
// Base - Method2
// Derived - Method1
// Derived - Method2
// Derived - Method1
// Base - Method2