作为介绍,我正在为个人学习目的创建一个基本的四叉树引擎。我希望这个引擎能够处理许多不同类型的形状(目前我正在处理圆形和正方形),它们将在窗口中四处移动并在发生碰撞时执行某种 Action 。
这是我目前拥有的形状对象:
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#;显然已经有一段时间了......
最佳答案
你需要使用向下转型
使用基类将对象存储在列表中
List<QShape> shapes = new List<QShape>
如果你知道它是什么,你就可以安全地向上转换对象,例如
if(shapes[0] is QSquare)
{
QSquare square = (QSquare)shapes[0]
}
你也可以隐式向下转型对象
QSquare square = new Square(5,0,0,"Blue");
QShape shape = square
For more information read the Upcasting and Downcasting sections here
关于c# - 在 C# 中创建对象的通用列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11354620/