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

标签 c# list generics object quadtree

作为介绍,我正在为个人学习目的创建一个基本的四叉树引擎。我希望这个引擎能够处理许多不同类型的形状(目前我正在处理圆形和正方形),它们将在窗口中四处移动并在发生碰撞时执行某种 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/

相关文章:

c# - 如何在 .NET Core 2.0 中包含库

python - 使用 argparse,如何将用户输入放入列表中?

java - java中的泛型方法

python - 如何将 json 嵌套数据集或 xml 嵌套数据集转换为元组列表?

python - 如果值为空,则拆分字典列表?

java - 了解 Java 泛型的类型安全异常

java - 创建通用 HashMap 数组

c# - 创建新线程的测试方法和我们从事件中获得的结果(NUnit 2.6)

c# - 了解 ObjectDataSource 和选择参数

c# - NamedPipeServerStream 接收 MAX=1024 字节,为什么?