gli*_*ite 4 .net c# wpf inheritance shape
为什么我不能使用继承Shapes类的类?
我需要Rectangle用一些方法扩展类,但是我想以我使用的方式使用这个类,我该Shape怎么办?
正如乔恩指出的那样,矩形是密封的.
根据您的目的,有两个选项:
您可以使用包含Rectangle的类来扩展Shape,并通过合成扩充功能.这些对象不会被视为"是"检查的矩形.
您可以为Rectangle编写扩展方法,然后可以在任何Rectangle上使用它们.然后,对象仍将被视为矩形.
例如
public static class RectangleExtensions {
public static bool IsSquare(this Rectangle r) {
return r.Width == r.Height;
}
}
Run Code Online (Sandbox Code Playgroud)