无法为数组赋值
我有一个 Texture2D 类型的图块数组,并且希望将数组中的每个图块设置为不同的值。
for (int i = 1; i <= columns * rows; i++)
{
m_tiles[i] = new Texture2D(m_graphicsDevice, tilewidth, tileheight);
}
它指出错误是结束 }
我不明白当我试图将其设置为非空时它是如何影响它的。如果我永远无法将变量设置为任何值,那么它们将始终为空。
我已经尝试过:
Texture2D[] m_tiles = new Texture2D(m_graphicsDevice, tilewidth, tileheight)[500];
但编译器说“无法将 [] 索引应用到‘Microsoft.Xna.Framework.Graphics.Texture2D’类型的表达式”
I have an array of tiles that are of the type Texture2D and want to set each one in the array to something different.
for (int i = 1; i <= columns * rows; i++)
{
m_tiles[i] = new Texture2D(m_graphicsDevice, tilewidth, tileheight);
}
It points to the error being the closing }
I don't understand how it being null when I'm trying to set it to not be null effects it. If I can never set the variable to anything then they'll always be null.
I have tried:
Texture2D[] m_tiles = new Texture2D(m_graphicsDevice, tilewidth, tileheight)[500];
But the compiler says "Cannot apply indexing with [] to and expression of type 'Microsoft.Xna.Framework.Graphics.Texture2D'"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您首先需要初始化一个数组实例,以便为其元素赋值:
在
for
循环之前添加以下语句:在 C# 中,数组索引是从 0 开始的,据我所知大多数 .NET 语言。因此,在使用索引器时,您可能希望从 0 .. n-1 循环,而不是 1 .. n。
但老实说,我很少在 .NET 中使用数组。如果您没有特定原因使用数组,我建议使用
列表
:You'll first need to initialize an array instance in order to assign values to its elements:
Preceed the
for
-loop with following statement:Arrays indices are 0-based in C#, and afaik most .NET languages. So when using the indexer, you might want to loop from 0 .. n-1, instead of 1 .. n.
But honestly, I rarely ever still use arrays in .NET. If you have no specific reason to use an array, I would recommend to use a
List<T>
:您需要首先实例化数组,例如:
像大多数其他类型一样,需要创建数组,更具体地说,它需要知道您希望它有多少个元素(在本例中,它有 10 个“槽”)。
You need to instantiate the array first, like:
Like most other types, arrays need to be created, more specifically it needs to know how many elements you want it to have (in this case, it has 10 "slots").
您需要使用适当的维度来初始化数组。
m_tiles[] 可能未初始化为接收(列 * 行)元素。
因此,在循环之前,您应该使用此大小初始化 m_titles 数组。
因此,如果您有 1 列和 1 行,它将为您提供 1 个槽 (
m_tiles[0]
)。如果您有 2 列和 2 行,您将有 4 个槽 (m_tiles[0],m_tiles[1],m_tiles[2],m_tiles[3]
);您应该以 i = 0 开始循环,否则,将不会分配 [0] 并且将触发索引越界异常。如果您确实不想从 0 开始,可以使用 (columns * rows +1) 将数组的大小增加 1。
You need to initialize the array with a proper dimension.
m_tiles[] may not be initialized to receive (columns * rows) elements.
So, before your loop, you should initialize the m_titles array with this size.
So, if you have 1 columns and 1 rows, it will give you 1 slot (
m_tiles[0]
). If you have 2 columns and 2 rows you will have 4 slots (m_tiles[0],m_tiles[1],m_tiles[2],m_tiles[3]
);You should start you loop with i = 0 otherwise, the [0] won't be assigned and an exception of index out of bound will be trigged. If you really do not want to start with 0, you can increase by 1 the size of the array using (columns * rows +1).