Vb.net 通过属性指定给结构的变量

Vb.net 通过属性指定给结构的变量,vb.net,properties,variable-assignment,Vb.net,Properties,Variable Assignment,我有以下几点 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 S

我有以下几点

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类中的属性分配给我?我做错了什么?

答案如下:

' 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.
前文最后一句话 示例失败,因为它只创建 该点的临时分配 位置返回的结构 财产。结构是一种值类型, 临时构筑物不存在 在语句运行后保留。这个 通过声明和 使用变量作为位置 创建更永久的分配 对于点结构。以下 示例显示了可以替换的代码 前文最后一句话 例如

这是因为struct只是一个临时变量。因此,解决方案是创建一个您需要的类型的新结构,为其分配所有内部变量,然后将该结构分配给类的struct属性。

您可以这样做

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

非常奇怪,不是我所期望的行为,
I
的保护/可接受性水平是相关的,但我同意这不是问题所在