成员隐藏
父类成员不用修饰符,子类隐藏成员用new修饰符修饰(可以省略)。
当子类隐藏父类成员时,若父类向下生成子类实例,则父类成员不会被隐藏,而会调用父类成员;只有当子类生成子类实例时,才会隐藏父类成员,转而使用子类成员。
上代码:
using System;
namespace test
{
public class Humanoid
{
public void Yell()
{
Console.WriteLine("Humanoid version of the Yell() method");
}
}
public class Enemy1 : Humanoid
{
public new void Yell()
{
Console.WriteLine("Enemy1 version of the Yell() method");
}
}
public class Enemy2 : Humanoid
{
public new void Yell()
{
Console.WriteLine("Enemy2 version of the Yell() method");
}
}
class Program
{
static void Main(string[] args)
{
Humanoid human = new Humanoid();
Humanoid enemy1 = new Enemy1();
Enemy2 enemy2 = new Enemy2();
human.Yell();
enemy1.Yell();
enemy2.Yell();
Console.ReadKey();
}
}
}
结果如下:
Humanoid version of the Yell() method
Humanoid version of the Yell() method
Enemy2 version of the Yell() method
重写
父类成员必须用virtual修饰符,子类中要重写的成员必须用override修饰符修饰。
当子类重写父类成员时,若父类向下生成子类实例,则父类成员会被重写,会调用子类成员;当子类生成子类实例时,也会重写父类成员,使用子类成员。
同样代码:
using System;
namespace test
{
public class Humanoid
{
public virtual void Yell()
{
Console.WriteLine("Humanoid version of the Yell() method");
}
}
public class Enemy1 : Humanoid
{
public override void Yell()
{
Console.WriteLine("Enemy1 version of the Yell() method");
}
}
public class Enemy2 : Humanoid
{
public override void Yell()
{
Console.WriteLine("Enemy2 version of the Yell() method");
}
}
public class Enemy3 : Humanoid
{
public void Yell()
{
Console.WriteLine("Enemy3 version of the Yell() method");
}
}
public class Enemy4 : Humanoid
{
public void Yell()
{
Console.WriteLine("Enemy4 version of the Yell() method");
}
}
class Program
{
static void Main(string[] args)
{
Humanoid human = new Humanoid();
Humanoid enemy1 = new Enemy1();
Enemy2 enemy2 = new Enemy2();
Humanoid enemy3 = new Enemy3();
Enemy4 enemy4 = new Enemy4();
human.Yell();
enemy1.Yell();
enemy2.Yell();
enemy3.Yell();
enemy4.Yell();
Console.ReadKey();
}
}
}
结果如下:
Humanoid version of the Yell() method
Enemy1 version of the Yell() method
Enemy2 version of the Yell() method
Humanoid version of the Yell() method
Enemy4 version of the Yell() method