Properties in Structures: “Expression is a value a

2019-04-23 02:50发布

问题:

I have the following 2 structures, and I don't really understand why the second one does not work:

Module Module1    
  Sub Main()
    Dim myHuman As HumanStruct
    myHuman.Left.Length = 70
    myHuman.Right.Length = 70

    Dim myHuman1 As HumanStruct1
    myHuman1.Left.Length = 70
    myHuman1.Right.Length = 70    
  End Sub

  Structure HandStruct
    Dim Length As Integer
  End Structure

  Structure HumanStruct
    Dim Left As HandStruct
    Dim Right As HandStruct
  End Structure

  Structure HumanStruct1
    Dim Left As HandStruct
    Private _Right As HandStruct
    Public Property Right As HandStruct
      Get
        Return _Right
      End Get
      Set(value As HandStruct)
        _Right = value
      End Set
    End Property    
  End Structure    
End Module

More detailed explanation: I have some obsolete code that uses structures instead of classes. So I need to identify a moment when a filed of this structure changes to the wrong value.

My solution to debug was to replace the structure filed by a property with the same name, and then I just set a breackpoint in the property setter to identify the moment when I receive the wrong value... in order do not rewrite all the code.... just for debugging purpose.

Now, I faced the problem above, so I don't know what to do... only setting the breakpoint everywhere this member of structure is assigned, but there is a lot of lines with that assignment...

回答1:

It's just a matter of what is happening when you run the program. The getter returns a copy of your struct, you set a value on it, then that copy of the struct goes out of scope (so the modified value doesn't do anything). The compiler shows this as an error since it is probably not what you intended. Do something like this:

Dim tempRightHand as HandStruct
tempRightHand = myHuman.Right
tempRightHand.Length = 70
myHuman.Right = tempRightHand

The left works because you are accessing it directly instead of through a property.