很奇怪的设计,需要靠着两个Keyword共同作用,才能完成多态——而不是类似Java那样的默认多态。所谓共同作用,即基类使用virtual 标示函数,子类使用override显示重写。
有点奇怪,MSDN说了一大堆情境,但我仍然认为增加了多义性与复杂性。
class MainClass
{
public static void Main (string[] args)
{
var s1 = new Student ("Jim");
s1.Say ();
s1.Do ();
var p1 = s1 as Person;
p1?.Say ();
p1?.Do ();
var s2 = p1 as Student;
s2?.Say ();
s2?.Do ();
}
}
class Person
{
public string Name { get; set;} = string.Empty;
public Person(string name)
{
Name = name;
}
public void Say()
{
WriteLine ($"{Name} Says:");
}
public virtual void Do()
{
WriteLine ($"{Name} Do:");
}
}
class Student : Person
{
public Student(string name) : base(name)
{
}
public void Say()
{
WriteLine ($"Student {Name} Says:");
}
public override void Do()
{
WriteLine ($"Student {Name} Do:");
}
}
Output:
Student Jim Says:
Student Jim Do:
Jim Says:
Student Jim Do:
Student Jim Says:
Student Jim Do:
不使用virtal & override在转型过程中并不会丢失实例信息,但是函数不存在多态特性。