c#虚函数需要在函数前加virtual
重写虚函数需要在函数前加override
using System;
class Program
{
static void Main(string[] args)
{
B obj1 = new B();
obj1.f();
obj1.g();
A obj2 = new B();
obj2.f();
obj2.g();
Console.ReadKey();
}
class A
{
int x = 1;
public void f()
{
Console.WriteLine($"A f {x}");
}
public virtual void g()
{
Console.WriteLine($"A g {x}");
}
}
class B: A
{
int x = 2;
public void f()
{
Console.WriteLine($"B f {x}");
}
public override void g()
{
Console.WriteLine($"B g {x}");
}
}
}
输出结果:
B f 2
B g 2
A f 1
B g 2