我有一个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%确定这段代码在引用方面做了什么。
我想我可以使用反射来设置属性,但我想还有一种更好的方法可以做到这一点。另一种实现我想要的方法是创建一个临时变量来存储矢量的副本,对其进行操作然后用副本替换list元素。
有没有办法让这更优雅?像(getReference(vertices,i)).Y = ...
?
错误是Expression is a value and therefore cannot be the target of an assignment。矢量是System.Windows.Vector
答案 0 :(得分:1)
问题是System.Windows.Vector是一个值类型(Structure)。当您访问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