我真的不明白--我应该什么时候使用虚拟函数?如果有人能给我解释一下,我会很高兴的,谢谢。
发布于 2011-06-29 20:12:36
虚方法是polymorphism的关键。标记为virtual的方法可以在派生类中重写,以更改或专门化该类的行为。
示例:
class Base
{
public virtual void SayHello()
{
Console.WriteLine("Hello from Base");
}
}
class Derived : Base
{
public override void SayHello()
{
Console.WriteLine("Hello from Derived");
}
}
static void Main()
{
Base x = new Base();
x.SayHello(); // Prints "Hello from Base"
x = new Derived();
x.SayHello(); // Prints "Hello from Derived"
}请注意,您可以重新声明(而不是覆盖)一个不是虚拟的方法,但在这种情况下,它不会参与多态性:
class Base
{
public void SayHello() // Not virtual
{
Console.WriteLine("Hello from Base");
}
}
class Derived : Base
{
public new void SayHello() // Hides method from base class
{
Console.WriteLine("Hello from Derived");
}
}
static void Main()
{
Base x = new Base();
x.SayHello(); // Prints "Hello from Base"
x = new Derived();
x.SayHello(); // Still prints "Hello from Base" because x is declared as Base
Derived y = new Derived();
y.SayHello(); // Prints "Hello from Derived" because y is declared as Derived
}发布于 2011-06-29 20:10:23
虚函数是子类可以根据需要重写的函数
//在父级中
public virtual string someMethod()
{
return "someting";
}//在子进程中
public override string someMethod()
{
return "someting else";
}发布于 2011-06-29 20:19:24
通过一个例子可能是最容易理解的,所以想象一下,我们有如下代码
class Base{
public virtual string VirtualMethod(){
return "base virtual";
}
public string NotVirtual(){
return "base non virtual";
}
}
class Derived : Base{
public override string VirtualMethod(){
return "Derived overriden";
}
public new string NotVirtual(){
return "new method defined in derived";
}
}
}如果您使用如下代码
Base b = new Base();
Derived d = new Derived();
Base b2 = d;
Console.WriteLine(b.VirtualMethod());
Console.WriteLine(d.VirtualMethod());
Console.WriteLine(b2.VirtualMethod());
Console.WriteLine(b.NotVirtual());
Console.WriteLine(d.NotVirtual());
Console.WriteLine(b2.NotVirtual());值得注意的是,b2和d是完全相同的对象!
上面的结果将是:
基本虚拟
派生覆盖
派生覆盖
基础非虚拟
在派生中定义的新方法
基础非虚拟
即使最后两行调用同一对象上的方法名NotVirtual。因为te变量被声明为基本变量和派生变量,并且该方法不是虚的,所以声明的变量类型确定所调用的方法,而如果该方法是虚的,则对象的运行时类型是将被调用的方法的决定因素
https://stackoverflow.com/questions/6520394
复制相似问题