我成功获取了记录列表,但问题是最后一条记录总是覆盖第一条记录。记录计数已经正确。这是我的代码。请帮忙。感谢。
Private Function MyFunction(ByVal myList As List(Of TT_GENERAL_CONFIGURATION))
Dim pConfig As New Config
Dim lst As New List(Of Config)
For Each MyCls As TT_GENERAL_CONFIGURATION In myList
pConfig.ConfigID = MyCls.INTERNAL_NUM
pConfig.ConfigType = MyCls.CONFIG_TYPE
pConfig.ConfigName = MyCls.CONFIG_NAME
pConfig.ConfigValue = MyCls.CONFIG_VALUE
lst.Add(pConfig)
Next
Return lst
End Function
答案 0 :(得分:2)
目前,您创建单个配置实例并将其多次添加到列表中。在每个循环中,您只修改此单个配置对象的值。在循环中移动配置创建:
Private Function MyFunction(ByVal myList As List(Of TT_GENERAL_CONFIGURATION))
Dim lst As New List(Of Config)
For Each MyCls As TT_GENERAL_CONFIGURATION In myList
Dim pConfig As New Config
pConfig.ConfigID = MyCls.INTERNAL_NUM
pConfig.ConfigType = MyCls.CONFIG_TYPE
pConfig.ConfigName = MyCls.CONFIG_NAME
pConfig.ConfigValue = MyCls.CONFIG_VALUE
lst.Add(pConfig)
Next
Return lst
End Function
答案 1 :(得分:0)
那是因为您正在重复使用对象的相同引用,这意味着您实际上并未添加新对象,而是对同一对象的新引用。您的代码应如下所示(“Config”类型的初始化在循环内移动):
Private Function MyFunction(ByVal myList As List(Of TT_GENERAL_CONFIGURATION))
Dim pConfig As Config
Dim lst As New List(Of Config)
For Each MyCls As TT_GENERAL_CONFIGURATION In myList
pConfig = New Config()
pConfig.ConfigID = MyCls.INTERNAL_NUM
pConfig.ConfigType = MyCls.CONFIG_TYPE
pConfig.ConfigName = MyCls.CONFIG_NAME
pConfig.ConfigValue = MyCls.CONFIG_VALUE
lst.Add(pConfig)
Next
Return lst
End Function
希望这有帮助。
答案 2 :(得分:0)
你只是实例化pConfig
一次,然后在你循环中你一遍又一遍地修改它在循环中移动实例化。