简体   繁体   English

没有合适的方法来覆盖c#,尽管有一个?

[英]No suitable method found to override c# despite there being one?

I was trying to find a solution here about this issue and I also feel my problem is very small but I cannot figure out what is going wrong. 我试图在这里找到一个关于这个问题的解决方案,我也觉得我的问题非常小,但我无法弄清楚出了什么问题。 It is telling me Rectangle.draw(): no suitable method found to override. 它告诉我Rectangle.draw():找不到合适的方法来覆盖。

    public interface shape 
    {
        void draw();
    }

    //concrete classes that implemenet interfaces
    public class Rectangle : shape 
    {
        public override void draw()
        {
            Console.WriteLine(this.GetType().Name + "'s inside function (generate stuff here) ");
        }
    }

The error is correct. 错误是正确的。 You can only override a method if it is present in an inherited base class. 如果方法存在于继承的基类中,则只能覆盖该方法。 Your Rectangle class doesn't inherit anything; 你的Rectangle类没有继承任何东西; it only implements the interface "shape". 它只实现了界面“形状”。

Remove the "override" keyword and everything will be fine. 删除“覆盖”关键字,一切都会好的。

The behavior of C# is a bit confusing at this point, especially for someone with a C++ background. 此时C#的行为有点令人困惑,特别是对于具有C ++背景的人。 Although behind the scenes, an interface works almost the same as an abstract base class, C# doesn't call an interface implementation an override. 虽然在幕后,界面与抽象基类几乎相同,但C#不会将接口实现称为覆盖。 This has one advantage: For each method, you can specify whether child classes can override the interface implementation or not. 这有一个优点:对于每个方法,您可以指定子类是否可以覆盖接口实现。 If you specify virtual when implementing your draw method, a class square that inherits from rectangle can implement its own draw method, if you specify nothing, square could not override draw. 如果指定virtual实现你的画法,上课的时候square ,从矩形继承了可以实现自己的绘制方法,如果你指定什么,方无法覆盖平局。 The later is helpful if you are forwarding calls to some (protected) method of the class only. 如果您仅将调用转发给类的某些(受保护)方法,则后者会很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM