gpt4 book ai didi

vb.net - VB.Net 2003 System.Collections.Generic 的解决方法?

转载 作者:行者123 更新时间:2023-12-02 21:52:10 25 4
gpt4 key购买 nike

我正在使用旧的 Web 应用程序 (vb.net 2003),并且尝试使用自定义类的通用列表。

我意识到 System.Collections.Generic 是根据 link 在 .Net 2 中引入的

除此列表之外还有其他选择吗?例如类数组?

假设我有以下类定义:

Public Class Box
Public x As Integer
Public y As Integer
End Class

还有一个 Class Box 数组:

Dim BoxList() As Box
BoxList(0).x = 1
BoxList(0).y = 1

BoxList(1).x = 2
BoxList(2).y = 2

但是当 BoxList(0).x = 1 错误时,我收到错误:对象引用未设置到对象的实例

我只是猜测。

最佳答案

使用ArrayList,如下所示:

Dim BoxList As New ArrayList
Dim box = New Box()
box.x = 1
box.y = 2
BoxList.Add(box)

注意:建议您向 Box 类添加一个构造函数,该构造函数将接受 xy 值,如下所示:

Public Class Box
Public x As Integer
Public y As Integer

Public Sub New(ByVal _x As Integer, ByVal _y As Integer)
x = _x
y = _y
End Sub
End Class

现在您可以将 ArrayList 代码缩短为:

Dim BoxList As New ArrayList
BoxList.Add(New Box(1, 2))

要使用 ArrayList 中的值,您需要将值从 ArrayList 中拆箱(不是双关语),如下所示:

For Each box In BoxList
' Use x value, like this
CType(box, Box).x
Next

或者(正如 Meta-Knight 建议的那样)

For Each box As Box In BoxList
' Now box is typed as Box and not object, so just use it
box.x
Next

关于vb.net - VB.Net 2003 System.Collections.Generic 的解决方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18383413/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com