创建TrendClass实例数组时datapoints属性被覆盖问题求助
问题根源:数组是引用类型
你遇到的问题核心是数组属于引用类型,而非值类型。在你的代码里,datapoints_array是在循环外声明的,所以所有TrendClass实例的.datapoints属性都指向同一个数组对象。每次循环修改datapoints_array的元素值,本质都是在修改同一块内存里的内容,最终所有实例都会共享最后一次循环修改后的数组数据。
解决方案:每次循环创建新的数组
要解决这个问题,只需要把datapoints_array的声明移到创建TrendClass实例的循环内部,这样每次迭代都会生成一个全新的数组对象,每个TrendClass实例都会持有独立的数组引用,不会再出现互相覆盖的情况。
修改后的完整代码如下:
Module Module1 Sub Main() testTrendclass() End Sub Public Function testTrendclass() As TrendClass() Dim array_length As Integer = 5 Dim Trend_array(array_length) As TrendClass Dim duration As Integer = 10 ' 将数组声明移到循环内部,每次创建新数组 For i = 0 To array_length Dim datapoints_array(duration) As Integer For i2 = 0 To 5 datapoints_array(i2) = i * i2 Next Trend_array(i) = New TrendClass With { .column_name = "ISO1_MICRA1810_" & i, .datapoints = datapoints_array, .timestamp = System.DateTime.Now().AddDays(i) } Console.WriteLine("current_data_array") For i2 As Integer = 0 To 4 Console.WriteLine("data_array: " & Trend_array(i).datapoints(i2)) Next Console.WriteLine(vbLf & vbLf) Next For i = 0 To Trend_array.Count() - 1 Console.WriteLine("column_name: " & Trend_array(i).column_name) For i2 As Integer = 0 To 4 Console.WriteLine("data_array: " & Trend_array(i).datapoints(i2)) Next Console.WriteLine("timestamp: " & Trend_array(i).timestamp & vbLf) Next Console.ReadLine() Return Trend_array End Function Public Class TrendClass Public Property timestamp As DateTime Public Property datapoints As Integer() Public Property column_name As String End Class End Module
补充说明
- 引用类型(比如数组、类实例)的赋值操作,传递的是内存地址的引用,而非数据副本。如果多个变量指向同一个引用类型对象,修改其中一个变量的内容,其他变量也会同步看到变化。
- 值类型(比如
Integer、DateTime)则相反,赋值时会创建数据副本,每个变量持有独立的数据,不会互相影响——这也是你的timestamp和column_name能正常保留的原因。
内容的提问来源于stack exchange,提问作者PoorCow
相关产品推荐
相关产品推荐

