私の学習曲線の中で私はList
とIEnumerable
をお互いに変換して遊んでいます。私はと驚いて何変数は同じインスタンスを参照
はEditMyList
手順MyIEnumerable
を実行した後MyList
として各DBTable
オブジェクトに対して同じデータが含まれていることです。しかし、私はMyIEnumerable
にList
が一度変更されていない限り、MyList
のみを変更しました。
ここで何が起こったのか、またMyList
とMyEInumerable
が同じインスタンスを参照する理由を説明できますか?
Public Class DBTable
Public Property TableName As String
Public Property NumberOfRows As Integer
End Class
Public Sub EditMyList
Dim MyList As New List(Of DBTable)
MyList.Add(New DBTable With {.TableName = "A", .NumberOfRows = 1})
MyList.Add(New DBTable With {.TableName = "B", .NumberOfRows = 2})
MyList.Add(New DBTable With {.TableName = "C", .NumberOfRows = 3})
Dim MyIEnumerable As IEnumerable(Of DBTable) = MyList
For Each item In MyList
item.NumberOfRows += 10
Next
End Sub
更新日:ケース終了bがaと等しくない場合。 String
も参照型であるため、ある変数を他の変数に代入すると、参照のみがコピーされます。しかしながら、端部に第一の例とは異なる結果が(@Sefeにより説明)ある
Dim a As String
Dim b As String
a = "aaa"
b = "bbb"
a = b
' At this point a and b have the same value of "bbb"
a = "xxx"
' At this point I would expect a and b equal to "xxx", however a="xxx" but b="bbb"
ここでは何が起こったのですか? MyListとMyIEnumerableは両方とも同じインスタンスを参照するため、リストは1つだけですが、参照は2つです。それはなぜ起こったのですか?参照を割り当てたので、 'Dim MyIEnumerable As IEnumerable(Of DBTable)= MyList'です。 –