无法inheritanceShapes
为什么我不能使用inheritanceShapes
类的类 ?
我需要用一些方法扩展Rectangle
类,但是我想以与使用Shape
相同的方式使用这个类,我该怎么办?
正如乔恩指出的那样,矩形是密封的。
根据您的尝试,有两个选项:
-
您可以使用包含Rectangle的类扩展Shape,并通过合成扩充function。 这些对象不会被视为“是”检查的矩形。
-
您可以为Rectangle编写扩展方法,然后可以在任何Rectangle上使用它们。 然后,对象仍将被视为矩形。
例如
public static class RectangleExtensions { public static bool IsSquare(this Rectangle r) { return r.Width == r.Height; } }
您可以编写一个派生自Shape
的类。 你不能写一个派生自Rectangle
的类,因为那是密封的。