c# - 基类的相同方法的不同返回类型

标签 c# inheritance overriding

一个非常简单的基类:

class Figure {
    public virtual void Draw() {
        Console.WriteLine("Drawing Figure");
    }
}

这个继承类:

class Rectangle : Figure
{
    public int Draw()
    {
        Console.WriteLine("Drawing Rectangle");
        return 42;
    }
}

编译器会提示 Rectangle 的“Draw”隐藏了 Figure 的 Draw,并要求我添加 newoverride 关键字。只需添加 new 即可解决此问题:

class Rectangle : Figure
{
    new public int Draw() //added new
    {
        Console.WriteLine("Drawing Rectangle");
        return 42;
    }
}

但是,Figure.Draw 的返回类型为 void,而 Rectangle.Draw 返回的是 int。我很惊讶这里允许不同的返回类型...这是为什么?

最佳答案

你真的读过new modifier吗? ?

Use the new modifier to explicitly hide a member inherited from a base class. To hide an inherited member, declare it in the derived class using the same name, and modify it with the new modifier.

因此,您隐藏了基类的版本。这两个方法具有相同名称这一事实并不意味着什么 - 它们与名称​​听起来相同的两个方法没有更多关系。


这种情况通常应该避免,但编译器总是知道要调用哪个方法,因此它是否有返回值。如果按如下方式访问“the”方法:

Figure r = new Rectangle();
r.Draw();

然后 FigureDraw 方法将被调用。没有产生返回值,也没有预期返回值。

关于c# - 基类的相同方法的不同返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11121404/

相关文章:

c++ - 在 C++ 中为抽象类模板创建接口(interface)

async-await - 如何在 C++ Cli 中重写异步方法?

c++ - 为什么调用基类函数而不是派生函数?

c# - Silverlight:在用户关注文本框时立即验证?

c# - 使用 C++ 包装器的托管代码中的 native C++ 实例

Django 模板大纲

java - 获取父对象而不传递其引用

c# - 这个 C# 语法的名称是什么?

c# - Task.ContinueWith() 父任务不等待子任务完成

java - 在java中重写具有更多参数的方法?