如果类中使用了abstract方法,则类也必须使用修饰符abstract
如果子类隐藏了父类中的非虚拟方法,则在这个方法之前必须使用new
如果子类想隐藏父类中的虚拟方法,则必须使用new,如果要覆盖父类中虚拟方法,则必须使用override
可以看出C#比C++这方面要求严格多了。
namespace hide
{
abstract class A{
public void F() { Console.WriteLine("F-A"); }
public virtual void G() { Console.WriteLine("G-A"); }
public abstract void Method3();
};
class B:A{
public new void F() { Console.WriteLine("F-B"); }
public override void G() { Console.WriteLine("G-B"); }
public override void Method3() { Console.WriteLine("Method3-B"); }
};
class Program
{
static void Main(string[] args)
{
B b = new B();
A a = b;
a.F();
b.F();
a.G();
b.G();
}
}
}
本文介绍了C#中方法隐藏与覆盖的规则,包括如何使用new关键字隐藏父类中的非虚拟方法及虚拟方法,以及如何使用override关键字正确覆盖父类中的虚拟方法。同时通过示例代码展示了抽象类与方法的实际应用。
1709

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



