2011-06-01 104 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