no suitable method found to override c#

前端 未结 2 1268
说谎
说谎 2021-01-17 16:44

I have tried a few things to fix the error and I just can\'t seem to figure this one out, I would greatly appreciate any help. The error is in both the Triangle and Square c

相关标签:
2条回答
  • 2021-01-17 16:46

    In your square and triangle classes, you need to remove the method parameter from ComputeArea() so that it matches the signature of the base class.

    0 讨论(0)
  • 2021-01-17 16:53

    Whenever you override a method, you have to override with the same signature as in the base class (there are exceptions for covariance and contravariance, but those don't apply to your question, so I'll ignore them here).

    In GeometricFigure, you have the declaration

    public abstract decimal ComputeArea();
    

    but in Square and Triangle you have the declaration

    public override decimal ComputeArea(decimal _area)
    {
        // ...
    }
    

    Let's say that some other class contained the following code:

    GeometricFigure fig = new Triangle(10, 10);
    decimal area = fig.ComputeArea();
    

    Which ComputeArea would be called? Triangle doesn't define a ComputeArea with no arguments, and neither does GeometricFigure, so there is no valid ComputeArea to call. As a result, the language spec disallows this scenario by requiring that override only be placed on methods that actually override methods of the base class, with the same number and type of arguments. Since ComputeArea(decimal) doesn't override ComputeArea(), the compiler errors out and tells you that you must place the override keyword on a ComputeArea() definition in Triangle, and that you can't put the override keyword on ComputeArea(decimal).

    That's not to say that you can't define a method ComputeArea(decimal) on Triangle and Square, but you can't declare it as overriding ComputeArea() in GeometricFigure.

    0 讨论(0)
提交回复
热议问题