将实际对象类型发送到重载函数

Ris*_*shi 0 c# polymorphism inheritance type-conversion

所以,请考虑以下情况

我有一个类型为"Shapes"的超类和继承Shapes的类"Box","Circle"和"Arrow".我有一个其他形状的列表,可以包含任何这些类型的成员.我需要通过列表进行枚举并绘制出每个形状.问题是每个形状的绘制方式不同,因此我有:

void Draw(Box b) {}

void Draw(Square s) {}

void Draw(Circle c) {}
Run Code Online (Sandbox Code Playgroud)

问题是,当我通过列表枚举时,返回的每个元素都是Shape类型(因为列表的类型是Shape),即使它的实际类型可能是Box.因此,没有任何过载被认为是正确的.

我有一个想法是创建一个临时对象并声明它是列表元素的实际类型.所以,假设list [i]是Circle类型

object o = Type.GetType(Convert.ToString(list[i].GetType()));
o = list[i];
Run Code Online (Sandbox Code Playgroud)

但是这仍然不起作用,因为现在编译器将'o'的类型识别为Object而不是Circle!

我怎样才能解决这个问题?

Joh*_*ers 8

DrawShape类中创建一个抽象方法.在每个派生类中重写它.让特定的形状自我绘制.


例:

public interface IDrawingSurface {
    // All your favorite graphics primitives
}

public abstract class Shape {
    public abstract void Draw();

    protected IDrawingSurface Surface {get;set;}

    public Shape(IDrawingSurface surface) {
        Surface = surface;
    }
}

public class Box {
    public Box(IDrawingSurface surface) : base(surface) {}
    public virtual void Draw(){ Surface.Something();... }
}

public class Square {
    public Square(IDrawingSurface surface) : base(surface) {}
    public virtual void Draw(){ Surface.Something();... }
}

public class Circle {
    public Circle(IDrawingSurface surface) : base(surface) {}
    public virtual void Draw(){ Surface.Something();... }
}
Run Code Online (Sandbox Code Playgroud)