簡體   English   中英

VB.net添加項目到List(of T)問題

[英]VB.net adding items to List(of T) issue

我正在加載包含7個對象的列表,但是這些對象被添加的最后一個對象“覆蓋”。 創建了7個對象(Exec,Mgr,Position ...等),第一個“ Exec”已正確添加到列表中,但是創建的每個新OrgShape都會覆蓋以前添加到列表中的所有OrgShape 。 我知道我想念一些簡單的事情...

Public Shared Function GetOrgShapeData() As List(Of OrgShape)
    Dim OgrShapeList As New List(Of OrgShape)
    Dim conn As OleDbConnection = HR_DB.GetConnection
    Dim strSQL As String
    strSQL = "SELECT * FROM VisioShapeDim"
    Dim selectCommand As New OleDbCommand(strSQL, conn)
    Try
        conn.Open()
        Dim reader As OleDbDataReader = selectCommand.ExecuteReader
        Dim orgshape As OrgShape
        Do While reader.Read
            orgshape = New OrgShape

            orgshape.ShapeName = reader("ShapeName")
            orgshape.ShapeWidth = reader("ShapeWidth")
            orgshape.ShapeHeight = reader("ShapeHeight")

            OgrShapeList.Add(orgshape)
            orgshape = Nothing
        Loop
        reader.Close()
    Catch ex As OleDbException
        Throw ex
    Finally
        conn.Close()
    End Try
    Return OgrShapeList
End Function

'**添加了OrgShape類

Public Class OrgShape
  Private Shared m_ShapeName As String
  Private Shared m_ShapeWidth As Double
  Private Shared m_ShapeHeight As Double

  Public Sub New()

  End Sub

  Public Shared Property ShapeName() As String
    Get
        Return m_ShapeName
    End Get
    Set(ByVal value As String)
        m_ShapeName = value
    End Set
  End Property

  Public Shared Property ShapeWidth() As Double
    Get
        Return m_ShapeWidth
    End Get
    Set(ByVal value As Double)
        m_ShapeWidth = value
    End Set
  End Property

  Public Shared Property ShapeHeight() As Double
    Get
        Return m_ShapeHeight
    End Get
    Set(ByVal value As Double)
        m_ShapeHeight = value
    End Set
  End Property
End Class

嘗試從屬性和變量中刪除Shared關鍵字,因為您正在尋找實例:

Public Class OrgShape
  Private m_ShapeName As String
  Private m_ShapeWidth As Double
  Private m_ShapeHeight As Double

  Public Property ShapeName() As String
    Get
      Return m_ShapeName
    End Get
    Set(ByVal value As String)
      m_ShapeName = value
    End Set
  End Property

請參見共享(Visual Basic)

您需要刪除以下行

orgshape = Nothing

您每次都在擦除對象。

請記住,.NET中的對象是reference類型。

根據問題編輯。 您也不能將共享字段和屬性用於實例數據。

我將在循環中使用Dim orgshape As new OrgShape並刪除orgshape = New OrgShapeorgshape = Nothing

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM