无法继承Shapes

gli*_*ite 4 .net c# wpf inheritance shape

为什么我不能使用继承Shapes类的类

我需要Rectangle用一些方法扩展类,但是我想以我使用的方式使用这个类,我该Shape怎么办?

Jon*_*eet 6

可以写一个派生自的类Shape.你不能写一个派生的类Rectangle,因为它是密封的.


Joe*_*tro 5

正如乔恩指出的那样,矩形是密封的.

根据您的目的,有两个选项:

  1. 您可以使用包含Rectangle的类来扩展Shape,并通过合成扩充功能.这些对象不会被视为"是"检查的矩形.

  2. 您可以为Rectangle编写扩展方法,然后可以在任何Rectangle上使用它们.然后,对象仍将被视为矩形.

例如

public static class RectangleExtensions {
    public static bool IsSquare(this Rectangle r) {
        return r.Width == r.Height;
    }
}
Run Code Online (Sandbox Code Playgroud)