【发布时间】:2012-07-06 01:05:44
【问题描述】:
作为介绍,我正在为个人学习目的创建一个基本的四叉树引擎。我希望这个引擎能够处理许多不同类型的形状(目前我正在使用圆形和正方形),它们都会在窗口中移动并在发生碰撞时执行某种动作。
这是我目前拥有的形状对象:
public class QShape {
public int x { get; set; }
public int y { get; set; }
public string colour { get; set; }
}
public class QCircle : QShape {
public int radius;
public QCircle(int theRadius, int theX, int theY, string theColour) {
this.radius = theRadius;
this.x = theX;
this.y = theY;
this.colour = theColour;
}
}
public class QSquare : QShape {
public int sideLength;
public QSquare(int theSideLength, int theX, int theY, string theColour) {
this.sideLength = theSideLength;
this.x = theX;
this.y = theY;
this.colour = theColour;
}
}
现在我的问题是,如何在 C# 中创建一个通用列表 (List<T> QObjectList = new List<T>();),这样我就可以拥有一个包含所有这些可能具有不同属性的各种形状的列表(例如,QCircle 具有“半径”属性,而 QSquare有“sideLength”属性)?一个实施示例也会有所帮助。
我只知道这个问题有一个非常明显的答案,但无论如何我都会很感激任何帮助。我正在尝试回到 C#;显然已经有一段时间了......
【问题讨论】:
-
列表
?? -
这样的列表会包括继承自 QShape 的类吗?如果是这样,我是对的;答案显而易见。
-
@Djentleman:是的。但是你只能访问 QShape 属性,除非你强制转换单个对象。
-
我能否以答案形式获得,包括您如何实现该功能的示例(即如何从 List
访问 QCircle 和 QSquare 特定属性)? -
@Djentleman 你不能。不知道为什么他的评论被赞成。您明确声明要访问不包含在父类中的不同属性,因此使用基类作为类型将不起作用。
标签: c# list generics object quadtree