4

这可能是我如何编写这篇文章的一个相当基本的问题,但我需要一些帮助:我有一个 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”中的条目数量相同,但它们都是空的

4

2 回答 2

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被声明为 aclass意味着它是一个引用类型,即类型的变量mp不是对象本身,而只是对它们的引用。所以如果我这样做:

Dim mp1 As New mp
Dim mp2 = mp1

我不会有两个mp对象,我会有两个对单个mp对象的引用。如果我更改对象的一个​​属性,则该更改将通过每个引用可见。

mp1.fg = "Test" 
mp2.fg = "Test2";
Console.WriteLine(mp1.fg) ' "Test2"
于 2013-08-19T14:29:41.077 回答
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
于 2013-08-19T14:29:07.067 回答