virtual和非virtual关键是在运行时候,而不是在编译时候.
1.如果非Virtual,编译器就使用声明的类对应的类型,也就是说,不是virtual的,在编译时候,就定了,比如例子:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplicationTest { class Program { static void Main(string[] args) { Father a = new Father(); a.s1 = "father"; a.VirFun(); Father b = new Son(); b.s1 = "son"; b.VirFun(); Father c = new Girl(); c.s1 = "girl"; c.VirFun(); Console.ReadLine(); } } public class Father { public string s1; public void VirFun() { Console.WriteLine(s1); } } public class Son : Father { public new void VirFun() { base.VirFun(); } } public class Girl : Father { public void VirFun() { base.VirFun(); } } }
运行结果:father,son,girl,都是执行的父类的方法
2,如果方法是Virtual的,然后子类使用了override, 编译器就生产代码。然后,在运行的时候,进行检测,看对象属于哪个类,然后调用这个类的方法。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplicationTest { class Program { static void Main(string[] args) { Father a = new Father(); a.s1 = "father"; a.VirFun(); Father b = new Son(); b.s1 = "son"; b.VirFun(); Father c = new Girl(); c.s1 = "girl"; c.VirFun(); Console.ReadLine(); } } public class Father { public string s1; public virtual void VirFun() { Console.WriteLine(s1); } } public class Son : Father { public override void VirFun() { base.VirFun(); } } public class Girl : Father { public override void VirFun() { base.VirFun(); } } }
运行结果:father,son,girl,执行的是子类的方法
3,如果一个父类的方法是virtual,子类不是用override,而是用new来覆盖了,那么运行子类的时候,还是执行声明的类的方法。比如下面的例子中,girl类对象就是。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplicationTest
{
class Program
{
static void Main(string[] args)
{
Father a = new Father();
a.s1 = "father";
a.VirFun();
Father b = new Son();
b.s1 = "son";
b.VirFun();
Father c = new Girl();
c.s1 = "girl";
c.VirFun();
Console.ReadLine();
}
}
public class Father
{
public string s1;
public virtual void VirFun()
{
Console.WriteLine(s1);
}
}
public class Son : Father
{
public new void VirFun()
{
base.VirFun();
}
}
public class Girl : Father
{
public new void VirFun()
{
base.VirFun();
}
}
}
运行结果:father,son,girl 执行的是父类方法,new声明的方法是一个“新”方法,与基类完全没有关系(虽然不幸与基类的某个方法同名同参)。所以对于父类的对象,根本就看不到。
虚拟方法与覆写
本文通过实例详细解析了C#中virtual与override关键字的区别。介绍了非virtual方法在编译期确定行为,而virtual方法结合override则能在运行时依据对象实际类型调用相应方法。
851

被折叠的 条评论
为什么被折叠?



