C # how to avoid type casting in a subclass?

Say I have a base Shape class. And then some subclasses like circle and square.

Next, create a method in another class called GetShape:

public Shape GetShape()
{
    return new Circle();  
}

Ok, so the idea is that I can go into shapeType and then get a strongly typed subclass of Shape. The above example is a massive simplification of the real code, but I think it makes sense.

So, how, when calling this method, it will look like

var shapeCreator = new ShapeCreator();
Circle myCircle = shapeCreator.GetShape(); 

The only problem is that it does not even start, since it requires a throw.

This really works:

Circle myCircle = (Circle) shapeCreator.GetShape(); 

I'm not alone with this actor, how can I avoid it and still follow the way to return the baseclass method so that I can return any compatible subclass.

+4
5

, . T ( Adil):

public T GetShape<T>() where T : Shape, new()
{
    return new T();
}
+5

, .

, shapeType, Shape

- :

var shape = shapecreator.GetShape(typeof(Circle));

var shape = shapecreator.GetShape<Circle>();

, ,

var circle = shapecreator.GetCircle();

, , , , , . if switch. , , , .

factory, ShapeFactoryBase virtual Shape Create() CircleFactory, , Create() . , , , , .

+3

, , , . Activator.Createinstance, .

GetShape

public T GetShape<T>() where T : Shape
{
    return (T)Activator.CreateInstance(typeof(T));
}

GetShape

Circle c = GetShape<Circle>();
Rectangle r = GetShape<Rectangle>();

. ,

, , :

public T GetShape<T>() where T : Shape, new()
{
    return new T();
}
+1

GetShape .

public static class GetShape {
    public class Circle() { .. }
    public class Square() { .. }
    public class Triangle() { .. }
    ...
}


var NewShape = new GetShape.Circle();

, .

+1

- Circle -, .

, safty .

0

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


All Articles