以下为重写基类方法代码:
class A
{
public virtual void M()
{
Console.WriteLine("A");
}
}
class B : A
{
public override void M()
{
Console.WriteLine("B");
}
}
class Program
{
static void Main(string[] args)
{
A a = new A();
A b = new B();
a.M();
b.M();
Console.Read();
}
}
输出:
A
B
隐藏基类方法代码:
class A
{
public void M()
{
Console.WriteLine("A");
}
}
class B : A
{
public void M()
{
Console.WriteLine("B");
}
}
class Program
{
static void Main(string[] args)
{
A a = new A();
A b = new B();
a.M();
b.M();
Console.Read();
}
}
输出:
A
A
顺便一提base指向直接父类。
本文介绍了C#中基类与派生类的方法重写和隐藏的区别,通过具体代码示例展示了重写与隐藏方法在运行时的不同表现。重写方法允许子类提供其特定实现,而隐藏方法则不会改变调用行为。
2780

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



