无法inheritanceShapes

为什么我不能使用inheritanceShapes类的类 ?

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

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

根据您的尝试,有两个选项:

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

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

例如

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

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