How to create a subclass inheriting from the Ellipse class

I'm new to C #, and I'm having trouble creating a subclass that inherits the properties of a certain class. I am using Visual Studio 2012 to create applications for Windows Phone 8.

I have no problem inheriting classes like Button or TextBox, but I can't inherit the Ellipse class. I can inherit the Shape class from which Ellipse is derived, but cannot Ellipse itself.

The idea is to add some properties to the ellipses that I create, so I can track in which order the user clicks these ellipses. I could use another class or use Ellipse itself (and play with existing properties), but for educational purposes I would like to know why I cannot (or how I can) inherit the Ellipse class.

public partial class Ball : Ellipse
{
     ...
}
+4
source share
4 answers

Since Ellipse sealed, and sealedmeans that "can not be inherited," you can not inherit it.

Alternatively, you can use the Decorator Pattern , which helps us extend the behavior of classes without inheritance.

public abstract class ShapeDecorator : Shape {
     protected Shape Shape {get; private set;}

     protected(Shape shape) {
          this.Shape = shape;
     }
}

public abstract class EllipseDecorator : ShapeDecorator {
      protected(Ellipse ellipse) : base(shape) {
      }

      public Ellipse Ellipse { get { (Ellipse)base.Shape; } }

      // Here, if you wish, you can override some methods using Ellipse features inside
      // So that your Shape acts as Ellipse
}

public class Ball : EllipseDecorator {
    public Ball() : base(new Ellipse()) {
         // you can initialize base.Ellipse here
    }

    // Now you can add your Ball specific methods here
    // You can still override some methods here
    // So that your ellipse acts as Ball
}

, - Ellipse, ball.Ellipse. Shape, Ball .

+3

. Ellipse sealed.

, .

public class MyEllipse: Shape
{
   private Ellipse _Ellipse;

   // pass through overridden Shape methods/properties to the underlying Ellipse

   // add custom methods/properties.
}
+6

Ellipse sealed:

public sealed class Ellipse : Shape

sealed

.

+5

, , . , . , .

+1

Source: https://habr.com/ru/post/1526768/


All Articles