vb.net 结构中的属性:“表达式是一个值,因此不能成为赋值的目标。”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18021810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 14:31:30  来源:igfitidea点击:

Properties in Structures: "Expression is a value and therefore cannot be the target of an assignment."

.netvb.netstructure

提问by serhio

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

enter image description here

在此处输入图片说明

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...

现在,我遇到了上面的问题,所以我不知道该怎么办......只在分配这个结构成员的任何地方设置断点,但是有很多行与该分配......

回答by Kevin DiTraglia

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:

这只是运行程序时发生了什么的问题。getter 返回您的结构的副本,您在其上设置一个值,然后该结构的副本超出范围(因此修改后的值不会执行任何操作)。编译器将此显示为错误,因为它可能不是您想要的。做这样的事情:

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.

左边是有效的,因为您是直接访问它而不是通过属性访问它。