2012-07-06 100 views
0

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

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

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; 
    } 
} 

所以我会最终希望有一个工程,以点一个界面,我可以使用泛型列表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(); 
} 

所以我的问题有两部分

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

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

+0

你又来了! Hehe = p – Pete 2012-07-06 04:53:53

+0

我可以说什么,我似乎无法离开:P – Djentleman 2012-07-06 10:44:54

回答

4

堆栈溢出是因为:

public Vector2 position { 
    get { return position; } 
    set { position = value; } 
} 

设定实际上再次设置相同。您可能希望这样:

private Vector2 _position; 
public Vector2 position { 
    get { return _position; } 
    set { _position = value; } 
} 

或它的短版:

public Vector2 position { get; set; } //BTW, the c# standard is to use upper camel case property names 

关于使用多态的,似乎就在这种情况下。

+0

选择这个答案,因为你涵盖了我的两个问题。谢谢 :) – Djentleman 2012-07-06 09:25:11

6

的问题是在你的财产是自己设定的圆形环

public Vector2 position { get ; set ; } 

或声明私有字段

private Vector2 _position; 
public Vector2 position { 
    get { return _position; } 
    set { _position = value; } 
}