Cannot inherit Shapes

孤街浪徒 提交于 2019-12-10 06:15:14

问题


Why I can't use a class that inherits a Shapes class?

I need to extend the Rectangle class with some methods, but i want to use this class in the same way I use a Shape, how can I do?


回答1:


As Jon pointed out, Rectangle is sealed.

Depending on what you're trying to do, a couple options are:

  1. You can extend Shape with your own class that contains Rectangle, and augment the functionality through composition. These objects wouldn't be considered Rectangles from an "is" check.

  2. You can write extension methods for Rectangle, and then you can use them on any Rectangle. Then the objects would still be considered Rectangles.

e.g.

public static class RectangleExtensions {
    public static bool IsSquare(this Rectangle r) {
        return r.Width == r.Height;
    }
}



回答2:


You can write a class which derives from Shape. You can't write a class which derives from Rectangle, because that's sealed.



来源:https://stackoverflow.com/questions/11142654/cannot-inherit-shapes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!