我將StateProp()定義爲動作屬性Public Property StateProp() As Action
。
調用StateProp()
方法將導致錯誤:屬性訪問必須分配給屬性或使用它的值。
當Action是一個字段而不是一個屬性時,做同樣的工作就可以正常工作(請參閱示例代碼的第一行)。 在C#中的相同代碼將工作得很好,但它需要它在VB中...當使用Action作爲屬性(而不是字段)時,調用該方法會導致錯誤:屬性訪問必須分配給屬性或使用其值
下面是對問題的演示。它將不會編譯,直到對StateProp()的調用被刪除。 我該如何做這項工作?
Module Module1
Sub Main()
Dim State As Action
State = AddressOf DoSomething1
State()
State = AddressOf DoSomething2
State()
Console.ReadLine() 'all the above works fine.
StateProp = AddressOf DoSomething1
'StateProp() ' **************** uncommenting this call causes compilation error: Property access must assign To the Property Or use its value.
Console.ReadLine()
End Sub
'trying to use this bit fails.
Dim m_checkstate As Action
Public Property StateProp() As Action
Get
Return m_checkstate
End Get
Set
Console.WriteLine("Changing state. Do some work")
m_checkstate = Value
End Set
End Property
Sub DoSomething1()
Console.WriteLine("Something1")
End Sub
Sub DoSomething2()
Console.WriteLine("Something2")
End Sub
End Module
'StateProp.Invoke()' – TnTinMn
@TnTinMn感謝。請將它作爲答案發布,以便我可以將其標記爲已回答。 – Guy