一个非常简单的基类:
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,并要求我添加 new
或 override
关键字。只需添加 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();
然后 Figure
的 Draw
方法将被调用。没有产生返回值,也没有预期返回值。
关于c# - 基类的相同方法的不同返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11121404/