例子:
class Child1 : Parent1
{
public new void show()
{
Console.WriteLine("Child1: hello.");
}
}
class Parent1
{
public void show()
{
Console.WriteLine("Parrent1: hello.");
}
}
static void Main(string[] args)
{
// new方法实验
Parent1 p1 ;
Child1 c1;
// 父类 = 父类
p1 = new Parent1();
p1.show(); // Parent1: hello
// 父类 = 子类
p1 = new Child1(); // 实验后得:这个是唯一特殊的并且正确的用法 父节点=子节点
p1.show(); // Parent1: hello
// 子类 = 父类 错误和虚函数一样不能这样写
// c1 = (Child1)new Parent1(); // 必须有一个转换不然无法通过编译 ,通过编译并且运行到这里报错
// c1.show();
// 子类 = 子类
c1 = new Child1();
c1.show(); // Child1: hello
}
总结:
父类 = 父类 = show(父类)// 没毛病
父类 = 子类 = show(父类)// 唯一难度用法
子类 = 父类 = show(错误)// 用法错误
子类 = 子类 = show (子类)//没毛病
new:调用的show,为 左边变量(正好和虚方法相反)