2011-06-01 54 views
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 

我的问题是,为什么我不能过我的财产在酒吧类分配给我?我做错了什么?

+0

很奇怪,不是行为我期待 – Jodrell 2011-06-01 11:40:36

+0

同样的事情更直接的方式'我'的保护/访问级别是相关的,但我同意不是问题 – Jodrell 2011-06-01 12:07:29

回答

3

答案是发现here,它说以下内容:

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

前面 示例的最后声明,因为它创建仅 由位置返回的点 结构的临时分配失败 属性。结构是一个值类型, 并且该语句运行后保留的临时结构不是 。 问题通过声明和 使用位置变量来解决,其中 为Point结构创建更多永久性分配 。以下 示例显示的代码可以取代 前面 示例的最后一条语句。

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

+0

我们同意,有效 – Jodrell 2011-06-01 11:50:00

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