利用C#中的多态接口

Dje*_*man 0 c# stack-overflow polymorphism interface quadtree

通过介绍,我正在为个人学习目的创建一个基本的Quadtree引擎.我希望这个引擎能够处理许多不同类型的形状(目前我正在使用圆形和方形),这些形状将在窗口中移动并在发生碰撞时执行某种操作.

在先前询问关于通用列表主题的问题后,我决定使用多态性接口.最好的界面是一个界面利用,Vector2因为我的四叉树中出现的每个对象都有一个x,y位置,Vector2并且很好地覆盖了它.这是我目前的代码:

public interface ISpatialNode {
    Vector2 position { get; set; }
}

public class QShape {
    public string colour { get; set; }
}

public class QCircle : QShape, ISpatialNode {
    public int radius;
    public Vector2 position {
        get { return position; }
        set { position = value; }
    }
    public QCircle(int theRadius, float theX, float theY, string theColour) {
        this.radius = theRadius;
        this.position = new Vector2(theX, theY);
        this.colour = theColour;
    }
}

public class QSquare : QShape, ISpatialNode {
    public int sideLength;
    public Vector2 position {
        get { return position; }
        set { position = value; }
    }
    public QSquare(int theSideLength, float theX, float theY, string theColour) {
        this.sideLength = theSideLength;
        this.position = new Vector2(theX, theY);
        this.colour = theColour;
    }
}
Run Code Online (Sandbox Code Playgroud)

所以,我会最终希望有一个工程,我可以使用泛型列表点的接口List<ISpatialNode> QObjectList = new List<ISpatialNode>();,我可以使用代码添加形状它QObjectList.Add(new QCircle(50, 400, 300, "Red"));还是QObjectList.Add(new QSquare(100, 400, 300, "Blue"));沿着这些线路或某事(记住,我会想沿线添加不同的形状).

问题是,当我从这里调用它时,这个代码似乎不起作用(Initialize()是XNA方法):

protected override void Initialize() {
    QObjectList.Add(new QCircle(5, 10, 10, "Red"));

    base.Initialize();
}
Run Code Online (Sandbox Code Playgroud)

所以我的问题有两个部分:

1.为什么这段代码会在set { position = value; }QCircleQSquare类的部分给出一个stackoverflow错误?

2.这是一种利用多态接口的有效/有效方法吗?

Asi*_*taq 6

问题在于你的属性它是在循环循环中设置自己

public Vector2 position { get ; set ; }
Run Code Online (Sandbox Code Playgroud)

或者声明一个私人领域

private Vector2 _position;
public Vector2 position {
    get { return _position; }
    set { _position = value; }
}
Run Code Online (Sandbox Code Playgroud)