如何在C#中声明对象数组 [英] How to declare an array of objects in C#

查看:113
本文介绍了如何在C#中声明对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a very beginning C# question. Suppose I have a class called GameObject, and I want to create an array of GameObject entities. I could think of writing code like:

GameObject[] houses = new GameObject[200];

编译器抱怨(假设由于语法无效).由于这是XNA开发,因此我将纹理加载到 LoadContent()方法中,如下所示:

The compiler complains (assuming because of invalid syntax). Since this is XNA development, I load my texture in the LoadContent() method as follows:

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

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

where houses[0] should be a GameObject and can be loaded like this, but the compiler throws this error:

"使用新"创建对象实例的关键字"

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

"在调用方法之前检查以确定对象是否为空"

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

我的初始化肯定有问题.

There must be something wrong with my initialization.

推荐答案

这里的问题是您已经初始化了 array ,但尚未初始化其 elements .它们都是空的.因此,如果您尝试引用 houses [0] ,它将为 null .

The issue here is that you've initialized your array, but not its elements; they are all null. So if you try to reference houses[0], it will be null.

这是一个很棒的小帮手方法,您可以自己编写:

Here's a great little helper method you could write for yourself:

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 数组初始化为:

Then you could initialize your houses array as:

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

这篇关于如何在C#中声明对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆