通过属性将结构体的值分配给变量

3
我有以下内容。
Public Structure Foo
   dim i as integer
End Structure

Public Class Bar

Public Property MyFoo as Foo
Get
   return Foo
End Get
Set(ByVal value as Foo)
   foo  = value
End Set

dim foo as Foo    
End Class

Public Class Other

   Public Sub SomeFunc()    
     dim B as New Bar()    
     B.MyFoo = new Foo()    
     B.MyFoo.i = 14 'Expression is a value and therefore cannot be the target of an assignment ???    
   End Sub
End Class

我的问题是,为什么我不能通过Bar类中的属性来赋值给i?我做错了什么?


非常奇怪,不是我预期的行为。 - Jodrell
i的保护/可访问级别是相关的,但我同意这不是问题。 - Jodrell
2个回答

3
答案在这里,它说:

' Assume this code runs inside Form1.
Dim exitButton As New System.Windows.Forms.Button()
exitButton.Text = "Exit this form"
exitButton.Location.X = 140
' The preceding line is an ERROR because of no storage for Location.

在上面的示例中,最后一条语句失败了,因为它仅为Location属性返回的Point结构创建了一个临时分配。结构是值类型,临时结构在语句运行后不会被保留。问题可以通过声明和使用Location变量来解决,这将为Point结构创建更永久的分配。以下示例显示了可以替换上一个示例中最后一条语句的代码。
这是因为结构体只是一个临时变量。因此解决方案是创建一个所需类型的新结构体,将其所有内部变量赋值,然后将该结构体分配给类的结构体属性。

1

你可以这样做

Dim b as New Bar()
Dim newFoo As New Foo()
newFoo.i = 14
b.MyFoo = newFoo

为了解决这个问题。

尝试使用以下代码在C#中实现相同的功能

class Program
{
    public void Main()
    {
        Bar bar = new Bar();
        bar.foo = new Foo();
        bar.foo.i = 14;
        //You get, Cannot modify the return value of ...bar.foo
        //    because it is not a variable
    }
}
struct Foo
{
    public int i { get; set; }
}

class Bar
{
    public Foo foo { get; set; }
}

我认为这是一种更直接的表达方式,与其说

Expression is a value and therefore cannot be the target of an assignment

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接