【问题标题】:Why won't this list of struct allow me to assign values to the field?为什么这个结构列表不允许我为字段赋值?
【发布时间】:2012-03-06 07:27:26
【问题描述】:
Public Structure testStruct
    Dim blah as integer
    Dim foo as string
    Dim bar as double
End Structure

'in another file ....

Public Function blahFooBar() as Boolean
    Dim tStrList as List (Of testStruct) = new List (Of testStruct)

    For i as integer = 0 To 10
        tStrList.Add(new testStruct)
        tStrList.Item(i).blah = 1
        tStrList.Item(i).foo = "Why won't I work?"
        tStrList.Item(i).bar = 100.100

        'last 3 lines give me error below
    Next

    return True
End Function

我得到的错误是:表达式是一个值,因此不能成为赋值的目标。

为什么?

【问题讨论】:

  • 简单的解决方案:不要使用结构,使用类?

标签: vb.net .net-3.5


【解决方案1】:

我赞同使用类而不是结构的意见。

您遇到困难的原因是您的结构是值类型。当您访问列表中值类型的实例时,您将获得该值的副本。然后您尝试更改副本的值,这会导致错误。如果你使用了一个类,那么你的代码就会像写的那样工作。

【讨论】:

    【解决方案2】:

    在您的 For 循环中尝试以下操作:

    Dim tmp As New testStruct()     
    tmp.blah = 1
    tmp.foo = "Why won't I work?"
    tmp.bar = 100.100
    tStrList.Add(tmp)
    

    对此我认为这与 .NET 在您通过 List(of t) 访问结构时复制结构的方式有关。

    更多信息请见here

    【讨论】:

      【解决方案3】:

      尝试先创建对象

      Dim X = New testStruct 
      

      并在 THAT 上设置属性

      testStruct.blah = "fiddlesticks"
      

      在将其添加到列表之前。

      【讨论】:

      • 我打算这样做,但结构与类的工作方式不同。这意味着列表中的所有结构都指向同一个结构,而不是不同的结构。
      • 即使在构造函数中有 New ?有趣的。这是我要记住的。
      • 使用 New 将创建一个新的结构实例。
      • 我就是这么想的。但我认为这里的教训是:避免使用结构,而是使用类。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-08
      • 1970-01-01
      • 2018-10-09
      • 2013-09-07
      • 1970-01-01
      相关资源
      最近更新 更多