本文介绍了不能继承形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能用一个类继承一个的?

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?

推荐答案

随着乔恩指出,矩形是密封的。

As Jon pointed out, Rectangle is sealed.

根据你在做什么,一对夫妇的选项有:

Depending on what you're trying to do, a couple options are:

  1. 您可以扩展外形与您自己的类,它包含矩形,并通过成分增加的功能。这些对象不会从是检查被认为是矩形。

  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.

您可以写为矩形扩展方法,然后你就可以使用他们在任何矩形。然后,对象仍然会被认为是矩形。

You can write extension methods for Rectangle, and then you can use them on any Rectangle. Then the objects would still be considered Rectangles.

例如。

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

这篇关于不能继承形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 23:19