使用override进行一般方法重写
屏幕输出
![](https://tiantai.live/wp-content/uploads/2022/02/739b21e536c98e07b29b591e7f181535_012b5b4d-28cc-42ef-b875-200591dddd19.png)
可见,这种方法,无论如何转换类型,最终执行的都是子类的方法
(C#)
class Program
{
static void Main(string[] args)
{
S3 s = new S3();
// 调用S3.Methoed
s.Method();
// 调用S2.Methoed
((S2)s).Method();
// 调用S1.Methoed
((S1)s).Method();
Console.ReadLine();
}
}
class S1
{
public virtual void Method()
{
Console.WriteLine("这是S1实例方法");
}
}
class S2:S1
{
public override void Method()
{
Console.WriteLine("这是S2实例方法");
}
}
class S3 : S2
{
public override void Method()
{
Console.WriteLine("这是S3实例方法");
}
}
vb.net
Module Module1
Sub Main()
Dim s As New S3()
s.Method()
CType(s, S2).Method()
CType(s, S1).Method()
Console.ReadLine()
End Sub
End Module
Class S1
Public Overridable Sub Method()
Console.WriteLine("这是S1实例方法")
End Sub
End Class
Class S2
Inherits S1
Public Overrides Sub Method()
Console.WriteLine("这是S2实例方法")
End Sub
End Class
Class S3
Inherits S2
Public Overrides Sub Method()
Console.WriteLine("这是S3实例方法")
End Sub
End Class