C# vs Java - 为什么虚拟关键字是必要的?
2022-09-04 02:40:29
我开始学习一些C#,我遇到了一个令人不安的问题:虚拟方法。这样的关键字是必要的吗?
Java中的简单多态性不需要虚拟关键字工作,甚至覆盖加注也是可选的:
package figures;
public class Figures {
public static void main(String[] args) {
Figure figure = new Figure();
Circle circle = new Circle();
Triangle triangle = new Triangle();
Figure []arrayOfFigures = {figure, circle, triangle};
for (int i = 0; i < 3; i++){
arrayOfFigures[i].introduceYourself();
}
}
}
class Figure {
public void introduceYourself(){
System.out.println("I am just a figure.");
}
}
class Circle extends Figure {
@Override
public void introduceYourself() {
System.out.println("I am a circle.");
}
}
class Triangle extends Figure {
@Override
public void introduceYourself() {
System.out.println("I am a triangle.");
}
}
而在 C# 中,相同的示例需要 virtual
和 override
关键字才能工作:
namespace Figures
{
class Figures
{
static void Main(string[] args)
{
Figure figure = new Figure();
Circle circle = new Circle();
Triangle triangle = new Triangle();
Figure[] arrayOfFigures = { figure, circle, triangle };
for (int i = 0; i < 3; i++)
{
arrayOfFigures[i].IntroduceYourself();
}
}
}
}
class Figure
{
public virtual void IntroduceYourself()
{
System.Console.WriteLine("I am just a simple figure.");
}
}
class Circle : Figure
{
public override void IntroduceYourself()
{
System.Console.WriteLine("I am a circle.");
}
}
class Triangle : Figure
{
public override void IntroduceYourself()
{
System.Console.WriteLine("I am a triangle.");
}
}
通常有动机将一些关键字引入语言。由于C#是在Java和许多其他面向对象语言之后创建的,我想知道是否有理由引入强制性(多态性工作)和关键字?virtual
override