【问题标题】:Properties in Structures: "Expression is a value and therefore cannot be the target of an assignment."结构中的属性:“表达式是一个值,因此不能成为赋值的目标。”
【发布时间】:2013-08-02 16:24:33
【问题描述】:

我有以下2个结构,我不太明白为什么第二个不起作用:

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

更详细的解释:我有一些使用结构而不是类的过时代码。因此,我需要确定该结构的字段更改为错误值的时刻。

我的调试解决方案是用同名属性替换结构,然后我只是在属性设置器中设置一个断点来识别我收到错误值的时刻......为了不重写所有代码....仅用于调试目的。

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

【问题讨论】:

    标签: .net vb.net structure


    【解决方案1】:

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

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

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

    【讨论】:

    • 谢谢,凯文。我添加了一些解释为什么我做这个测试。
    • @serhio 没问题,在使用结构类型创建属性时总是会出现这种情况(例如TimeSpan)。 IIRC 它过去不是编译错误,根本无法工作,这可能更令人沮丧。
    • getter 返回此结构的副本...我可以强制它“byref”吗? )
    • @serhio 我不这么认为,在 .NET 中,结构总是按值传递。我不确定你是否能以某种方式 ByRef 属性获取器。
    • 它会烧毁所有东西来将你的结构更改为类吗?
    猜你喜欢
    • 1970-01-01
    • 2010-10-15
    • 2013-08-03
    • 2016-12-13
    • 1970-01-01
    • 1970-01-01
    • 2012-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多