如何在 C# 中使用动态分配来创建类对象数组?
我创建了一个名为 x 的类; 所以我想使用动态分配来制作它的数组
x [] myobjects = new x();
,但它给了我这个错误
无法将类型“ObjAssig4.x”隐式转换为“ObjAssig4.x[]”
我知道这是转储问题,但我是初学者,
谢谢
i made a class named x;
so i want to make array of it using dynamic allocation
x [] myobjects = new x();
but it gives me that error
Cannot implicitly convert type 'ObjAssig4.x' to 'ObjAssig4.x[]'
i know it's dump question but i am a beginner
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
对于数组,您不创建带有括号“new x()”的新数组
但数组不是动态的。
您可以使用 Array.Resize 来改变它的大小,但您可能需要一个 List
For an array you don't create a new one with parens 'new x()'
An array is not dynamic though.
You could use Array.Resize to alter it's size, but you're probably after a List
您不想使用数组,而是使用 列表
供您参考声明数组也是错误的。
应该是
x[] myobjects = new x[5];
You don't want to use an array but a list
FYI you were declaring the array wrong too.
It should be
x[] myobjects = new x[5];
创建对
x
类型对象的numberOfElements
引用数组。最初这些引用是空的。您必须独立创建对象 x 并将对它们的引用存储在您的数组中。您可以使用初始化列表创建一个数组和一些对象,这些对象的引用最终会出现在该数组中,如下所示:
Creates an array of
numberOfElements
references to objects of typex
. Initially those references are null. You have to create the objectsx
independently and store references to them in Your array.You can create an array and some objects whose references will end up in the array, using an initialisation list like:
我发现我可以做到这一点
i Found that i can do this
错误
告诉您您正在尝试声明一个新的 x 并将其分配给您的数组。相反,您需要声明一个新数组(还需要一个大小):
The error
is telling you that you are trying to declare a new x and assign it to your array. Instead, you need to declare a new array (which will also need a size):