将新项目添加到对象数组 [英] Add new item to Object Array
问题描述
我有一个对象数组,其中包含带有数组的对象.当我稍后尝试添加另一个对象时,出现错误提示
I have an object array containing objects with arrays. When i try to add another object later i get an error saying
'An exception of type 'System.MissingMemberException' occurred in
Microsoft.VisualBasic.dll but was not handled in user code
Additional information: Public member 'Add' on type 'Object()()' not found.'
这是我尝试添加新成员的方法
And here is how i try to add new member
Dim data As Object = {
New Object() {"Year", "Sales", "Expenses"},
New Object() {"2004", 1000, 400},
New Object() {"2005", 1170, 460},
New Object() {"2006", 660, 1120},
New Object() {"2007", 1030, 540}
}
Dim newObj = New Object() {"2008", 1030, 540}
data.Add(newObj) 'here the error occures
我尝试将数据更改为 List(of Object) 然后它起作用了但是 List 的格式后来不可接受(我将数据作为 json 发送到不同的 api).
I tried changing data to List(of Object) and then it worked but the format of List is not acceptable later (i send data to different api as json).
可能这很简单,但我是新手 :) 提前感谢您的帮助.
Probably it's easy issue but i'am kind of newbie :) Thanks for help in advance.
推荐答案
变量 data
是一个 Object
.Object
没有 Add
方法.但是由于您实际上将其声明为 Object()
(对象数组),因此您不能使用 Add
,因为数组具有固定大小.
The variable data
is an Object
. Object
has no Add
method. But since you actually declare it as Object()
(an array of objects) you cannot use Add
either because an array has a fixed size.
改为使用可以调整大小的List(Of Object)
:
Instead use a List(Of Object)
which can be resized:
Dim data As List(Of Object) = New List(Of Object) From
{
New Object() {"Year", "Sales", "Expenses"},
New Object() {"2004", 1000, 400},
New Object() {"2005", 1170, 460},
New Object() {"2006", 660, 1120},
New Object() {"2007", 1030, 540}
}
// ...
data.Add(newObj)
但是,如果要存储字符串,为什么还要使用对象呢?我会将其声明为 List(Of String)
,否则您总是需要将其拆箱到与装箱相同的类型,这样效率低下、可读性差且更容易出错.
However, why do you use objects at all if you want to store strings? I would declare it as List(Of String)
, otherwise you always need to unbox to the same type that was boxed which is inefficient, less readable and more error-prone.
如果您需要 Object()
,您可以在完成后使用 data.ToArray()
.
If you need an Object()
you can use data.ToArray()
when you're finished with it.
这篇关于将新项目添加到对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!