英文:
c# allocate memory for array?
问题
我正在尝试创建一个类的数组,但在赋值给数组时Unity报错了
对象引用未设置为对象的实例。
代码:
public class StringClass {
public string name;
}
private void JsonParsing()
{
StringClass[] stringClass = new StringClass[3]; // 我没有在这里创建数组的对象吗?
stringClass[0].name = "test0"; // 错误
stringClass[1].name = "test1";
stringClass[2].name = "test2";
stringClass[3].name = "test3";
字符串数组运行正常,但类数组不正常。
英文:
I'm trying to make a array of a class but Unity throwing error when assigning values to arrays
Object reference not set to an instance of an object.
The Code:
public class StringClass {
public string name;
}
private void JsonParsing()
{
StringClass[] stringClass = new StringClass[3]; // am i not creating object for array in here?
stringClass[0].name = "test0"; // Error
stringClass[1].name = "test1";
stringClass[2].name = "test2";
stringClass[3].name = "test3";
The string array works perfectly fine but the class arrays just don't work properly
答案1
得分: 0
感谢 @UnholySheep 指出了这里有两个问题。
数组大小
StringClass[3]
只是定义了数组的大小为 3。这意味着您可以使用数组索引 0-2。大小始终从 1 开始计数,而索引从 0 开始。
初始化数组元素
在数组中,您需要在设置其属性之前初始化每个元素。
在您的代码中,您只设置了数组的大小,但从未初始化任何元素。但您仍然尝试更改元素的属性,导致尝试访问空对象。
示例:
class StringClass
{
public string name;
}
internal class Program
{
private void JsonParsing()
{
/*
由于这不是值类型数组,
我们需要在修改任何属性之前初始化每个元素。
*/
StringClass[] stringClass = new StringClass[2];
// 初始化第一个索引的元素
stringClass[0] = new StringClass();
// 现在我们可以修改它!
stringClass[0].name = "test0";
// 在下一个索引上再次执行
stringClass[1] = new StringClass();
stringClass[1].name = "test1";
}
}
英文:
Thanks to @UnholySheep for pointing that there's two issues here.
Array sizes
StringClass[3]
is just defining the size of the array to be 3. Which means you can use the array indexes 0-2. Sizes are always counted from 1, while indexes start at 0.
Initiating array elements
In the array you will need to initiate each element before setting its properties.
In your code you only set the size of the array and never initiated any elements in it. But you still tried changing the properties of a element, resulting in trying to access a null object.
Example:
class StringClass
{
public string name;
}
internal class Program
{
private void JsonParsing()
{
/*
Since this isn't a value type array,
we need to initiate each element before
modifying any properties of it.
*/
StringClass[] stringClass = new StringClass[2];
// initiates the element of the first index
stringClass[0] = new StringClass();
// now we can modify this!
stringClass[0].name = "test0";
// Do it again on the next index
stringClass[1] = new StringClass();
stringClass[1].name = "test1";
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论