vb.net:列出变量而不是值

时间:2021-05-21 15:17:35

标签: arrays .net vb.net list

我需要的东西似乎并不特别,但不知何故 - 也许我在谷歌上搜索了错误的关键词 - 我没有在网上找到任何东西。

如何将变量(或对它们的引用?)存储在列表/数组/或类似的东西中,以便当我对列表应用更改时,更改也将应用到变量?

类似于:

Dim myList As New List(Of Object)
Dim a As Integer = 5

myList.Add(a)
myList(0) = 10    'here i want a to change as well

If a = 10 Then
    'This is exactly what I want
Else If a = 5 Then
    'This is what i don't want but what I will get
End If

那么我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

整数是值类型,而不是像类那样的引用类型。您有该值的两个副本,一次在列表中,一次在变量中。如果你想要这种行为,你需要在列表中存储一个引用类型。例如:

Public Class MyNumber
    Public Sub New(number As int32)
        Value = Number
    End Sub

    Public Property Value As Int32
End Class

Sub Main
    Dim myList As New List(Of MyNumber)
    Dim myFirstNumber As New MyNumber(5)
    myList.Add(myFirstNumber)
    myList(0).Value = 10 

    ' Now both, myFirstNumber.Value and myList(0).Value is 10
End Sub
相关问题