gpt4 book ai didi

c# - 如何在 C# 中声明一个对象数组

转载 作者:IT王子 更新时间:2023-10-29 03:51:11 24 4
gpt4 key购买 nike

我有一个非常初级的 C# 问题。假设我有一个名为 GameObject 的类,我想创建一个 GameObject 实体数组。我可以想到编写如下代码:

GameObject[] houses = new GameObject[200];

编译器报错(假设是因为语法无效)。由于这是 XNA 开发,我在 LoadContent() 方法中加载我的纹理,如下所示:

 houses[0].Model = Content.Load<Model>("Models\\Building_01 Windowed");

其中 houses[0] 应该是一个 GameObject 并且可以像这样加载,但是编译器会抛出这个错误:

"Use the "new" keyword to create an object instance"

"Check to determine if the object is null before calling the method"

一定是我的初始化有问题。

最佳答案

这里的问题是您已经初始化了您的数组,但没有初始化它的元素;他们都是空的。因此,如果您尝试引用 houses[0],它将是 null

这是您可以自己编写的一个很棒的小辅助方法:

T[] InitializeArray<T>(int length) where T : new()
{
T[] array = new T[length];
for (int i = 0; i < length; ++i)
{
array[i] = new T();
}

return array;
}

然后您可以将您的houses 数组初始化为:

GameObject[] houses = InitializeArray<GameObject>(200);

关于c# - 如何在 C# 中声明一个对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3301678/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com