public class Shapes
{
public virtual void Color()
{
Console.WriteLine("Shapes");
}
}
public class Square : Shapes
{
public void Color()
{
Console.WriteLine("Square");
}
}
public class Test
{
public static void main()
{
Shapes s1 = new Shapes();
s1.Color();
Shapes s2 = new Square();
s2.Color();
}
}
我想知道如果基类定义了一些虚方法,那么在派生类中是否必须覆盖它们?同样,如果基类方法是抽象的,我们需要在派生类中实现该方法,但是是否必须使用override修饰符?如果省略 override 修饰符会怎样。
最佳答案
I want to know if the base class has defined some methods virtual, then is it mandatory to override them in derive class?
绝对不是。由派生类决定是否覆盖虚拟方法。请注意,某些类会建议派生类在某些情况下重写特定的虚方法,但编译器不会强制执行。
If the base class method is abstract, we need to implement the method in derive class, but is override modifier is mandatory?
是的,需要使用override
关键字,否则方法会被派生类中的定义隐藏。
如果您实际运行您的代码,您会看到打印了两次“Shapes”。这是因为 Squares
类中的 Color()
方法未使用 override
关键字声明。因此,它隐藏基类方法。这意味着它只能通过 Squares
类型的变量访问:
Squares s3 = new Squares();
s3.Color();
这将打印“Square”,因为您是在正确类型的变量上调用该方法。
关于c# - 在 C# 中,override 修饰符在派生类中对于基类的虚拟/抽象方法是强制性的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7073537/