这可能是一个相当基本的问题,我如何写这个,但我需要一些帮助: 我有一个odject定义为一个公共类,有两个字段,两个字符串
Public Class mp
Dim _fg As String
Dim _scode As String
Property fg As String
Get
Return _fg
End Get
Set(ByVal value As String)
_fg = value
End Set
End Property
Property scode As String
Get
Return _scode
End Get
Set(ByVal value As String)
_scode = value
End Set
End PropertyEnd Class
然后我定义了这些数组:
Dim mps As New List(Of mp)()
然后在循环中,我首先清除它后开始添加到列表中:
Dim mpholder As New mp
cmd.CommandText = 'Query here
cmd.ExecuteNonQuery()
reader = cmd.ExecuteReader
mp.Clear()
Try
Do While reader.Read()
mpholder.fg = ""
mpholder.scode = ""
mpholder.fg = reader(0)
mpholder.scode = reader(1)
mps.Add(mpholder)
Loop
Catch ex As Exception
MP_Res.Text = "error"
End Try
如果我在某个阶段最终得到错误并进入捕获,列表'mp'中的条目数相同但它们都是空的
答案 0 :(得分:2)
您继续将相同的项目添加到列表中。
尝试移动线
Dim mpholder As New mp
在读取/添加循环中:
Do While reader.Read()
Dim mpholder As New mp
mpholder.fg = reader(0)
mpholder.scode = reader(1)
mps.Add(mpholder)
Loop
由于mp
被声明为class
,这意味着它是一个引用类型,即mp
类型的变量不是对象本身,而只是对它们的引用。所以,如果我这样做:
Dim mp1 As New mp
Dim mp2 = mp1
我不会有两个mp
个对象,我会对一个mp
个对象有两个引用。如果我更改了对象的一个属性,那么通过每个引用都可以看到该更改。
mp1.fg = "Test"
mp2.fg = "Test2";
Console.WriteLine(mp1.fg) ' "Test2"
答案 1 :(得分:1)
尝试以上方法。您只需要将对象创建到循环中。
cmd.CommandText = 'Query here
cmd.ExecuteNonQuery()
reader = cmd.ExecuteReader
Try
Do While reader.Read()
Dim mpholder As New mp
mpholder.fg = reader(0)
mpholder.scode = reader(1)
mps.Add(mpholder)
Loop
Catch ex As Exception
MP_Res.Text = "error"
End Try