在C#中创建通用的对象列表

Dje*_*man 9 c# generics list object quadtree

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

这是我到目前为止的形状对象:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我的问题是,如何List<T> QObjectList = new List<T>();在C#中创建一个通用列表(),这样我就可以有一个包含所有这些可能具有不同属性的各种形状的列表(例如,QCircle具有"radius"属性,而QSquare具有"sideLength"属性)?实施的一个例子也是有帮助的.

我只知道这个问题有一个愚蠢明显的答案,但无论如何我都会感激任何帮助.我想回到C#; 它显然已经有一段时间了......

Joe*_*oel 7

你需要使用向下转发

将对象存储在具有基类的列表中

 List<QShape> shapes = new List<QShape>
Run Code Online (Sandbox Code Playgroud)

然后,如果您知道它是什么,则可以安全地向上转换对象

if(shapes[0] is QSquare)
{
     QSquare square = (QSquare)shapes[0]
} 
Run Code Online (Sandbox Code Playgroud)

您还可以隐式地向下转换对象

QSquare square = new Square(5,0,0,"Blue");
QShape shape =  square
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请阅读此处的Upcasting和Downcasting部分

  • 如果您在处理泛型集合中的项目时需要测试类型和强制转换,则表明出现了问题. (2认同)
  • 我相信你可以在你的例子中使用**is**关键字,它已经有很长一段时间了.if(myObject是MyType) (2认同)