【问题标题】:vb.NET set property of list member objectvb.NET 设置列表成员对象的属性
【发布时间】:2016-02-11 13:27:25
【问题描述】:

我有一个List(Of Vector) 并想设置一个属性,例如。循环中列表的一个成员的向量Y。 为什么这条线不起作用?

vertices(i).Y = vertices(i).Y + vertices(i - 1).Y

但是当我像这样正常地将属性分配给向量时(向量不在列表中),它可以工作:

Dim testVertex As Vector = New Vector(0, 0)
testVertex.Y = vertices(i).Y + vertices(i - 1).Y

使用vertices.Item(i).Y 也不起作用。

我使用的代码是这样的:

Dim vertices As List(Of Vector) = New List(Of Vector)

' here we take absolute values in x-direction and
' relative values in y-direction which will be added up below

vertices.Add(New Vector(some_value, some_other_value))
' several more of the same line with other values

For i As Integer = 1 To vertices.Count - 1
    vertices(i).Y = vertices(i).Y + vertices(i - 1).Y
Next

这尤其令人困惑,因为我习惯了 C 风格的编程,而且这看起来可以使用指针轻松解决。我不是 100% 确定这段代码在引用方面做了什么。

我想我可以使用反射来设置属性,但我想还有更好的方法来做到这一点。实现我想要的另一种方法是创建一个临时变量来存储向量的副本,对其进行操作,然后用副本替换列表元素。

有没有办法更优雅地做到这一点? (getReference(vertices,i)).Y = ... 之类的东西?

错误是Expression is a value and therefore cannot be the target of an assignment。向量是System.Windows.Vector

【问题讨论】:

  • 第一个如何“不起作用”?这是什么意思?
  • 在 Visual Studio 中带有红色下划线,因此无法构建。
  • ...如果您将鼠标悬停在上面,编译器错误是什么?
  • 啊,错误是“表达式是一个值,因此不能成为赋值的目标”。 MSDN:msdn.microsoft.com/en-us/library/76435b93.aspx 但在 MSDN 上,唯一的帮助是您可以使用临时变量。
  • X 和 Y 之类的声音不是属性/公共字段。使用简单的道具显示Vector 的相关部分,它会正常工作

标签: vb.net list properties reference


【解决方案1】:

问题在于 System.Windows.Vector 是一个值类型(结构)。当您访问 List 中的实例时,您只会获得数据的副本,编译器会识别出您正在尝试修改副本。

您必须创建一个临时变量来保存 Vector 实例,然后设置属性,然后将其重新插入到列表中。像这样的:

Dim vertices As List(Of Vector) = New List(Of Vector)

' here we take absolute values in x-direction and
' relative values in y-direction which will be added up below

vertices.Add(New Vector(some_value, some_other_value))
' several more of the same line with other values

For i As Integer = 1 To vertices.Count - 1
    'get a copy of the Vectors
    Dim vTmp1 As Vector = vertices(i)
    Dim vTmp2 As Vector = vertices(i - 1)

    'Set the values
    vTmp1.Y = vTmp1.Y + vTmp2.Y

    'Put it back into the list, overwriting the value that is already there
    vertices(i) = vTmp1
Next

【讨论】:

    猜你喜欢
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-23
    • 1970-01-01
    • 1970-01-01
    • 2013-04-22
    • 1970-01-01
    相关资源
    最近更新 更多