通过介绍,我为个人学习目的创建了一个基本的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.为什么这段代码在我的QCircle
和QSquare
类的set { position = value; }
部分给我一个计算错误?
2.这是一种利用多态性接口的高效/有效方式吗?
你又来了! Hehe = p – Pete 2012-07-06 04:53:53
我可以说什么,我似乎无法离开:P – Djentleman 2012-07-06 10:44:54