【问题标题】:Changing dictionary entrys with a structure as value in Visual Basic 2012在 Visual Basic 2012 中使用结构作为值更改字典条目
【发布时间】:2014-01-14 09:04:59
【问题描述】:

我有这个结构:

Public Structure SourceDB
    Public SourceDBid As Integer
    Public SourceDBWimLocationName As String
    Public SourceDBDBName As String
    Public SourceDBIPAdress As String
    Public SourceDBPort As String
    Public SourceDBUsername As String
    Public SourceDBPassword As String
    Public ConnectivityState As String
    Public LastTransmittedId As Integer
End Structure

我以以下方式声明字典:

Private MySourceDBDictionary As New Dictionary(Of Integer, SourceDB)

现在值被添加到字典中...

有时我想在 for each 循环中更改字典的值:

For Each element As KeyValuePair(Of Integer, SourceDB) In MySourceDBDictionary
    MySourceDBDictionary.Item(element.Key).LastTransmittedId = 0
Next

由于某种原因,这不起作用...

错误代码是:表达式是一个值,因此不能作为赋值的目标。

它怎么可能,改变字典中已经存在的值???

亲切的问候!谢谢。

【问题讨论】:

    标签: vb.net visual-studio-2012 dictionary


    【解决方案1】:

    你想做的事不能用值类型来完成,但你可以通过读出结构并将其传回来做你想做的事。

        For Each element As KeyValuePair(Of Integer, SourceDB) In MySourceDBDictionary
            Dim src = MySourceDBDictionary(element.Key)
            src.LastTransmittedId = 0
            MySourceDBDictionary(element.Key) = src
        Next
    

    这会将完整的值类型替换为新的“值”

    或者,如果您使用Reference Type 而不是Value Type,即使用Class 而不是Structure,则可以使用您拥有的代码。我建议这个应该是一个类而不是一个结构,因为你在创建后修改值

    【讨论】:

      【解决方案2】:

      问题出在结构上看看这个问题Expression Is a value and therefore cannot be the target of an assignment

      上述问题应该很好地解释了何时应该使用Structure

      将您的结构更改为Class,您的代码应该可以工作, 你也可以把你的 foreach 循环稍微改成这样:

          For Each element As KeyValuePair(Of Integer, SourceDB) In MySourceDBDictionary
              element.Value.LastTransmittedId = 0
          Next
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-06
        • 1970-01-01
        • 2014-10-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-15
        相关资源
        最近更新 更多