Cannot inherit Shapes

2019-05-07 11:29发布

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?

2条回答
Luminary・发光体
2楼-- · 2019-05-07 11:48

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

查看更多
太酷不给撩
3楼-- · 2019-05-07 11:53

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;
    }
}
查看更多
登录 后发表回答