使用 Action 作为属性(而不是 Field)时,调用该方法会导致错误:属性访问必须分配给属性或使用其值

Guy*_*Guy 2 c# vb.net delegates

我将 StateProp() 定义为 Action Property Public Property StateProp() As Action
调用该StateProp()方法会导致错误:属性访问必须分配给属性或使用其值。
当 Action 是 Field 而不是 Property 时执行相同的操作可以正常工作(请参阅示例代码的第一行)。C# 中的相同代码可以正常工作,但在 VB 中需要它...

下面是问题的演示。在删除对 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
Run Code Online (Sandbox Code Playgroud)

TnT*_*nMn 5

这是一个完整的答案,而不是我之前在评论部分给出的简洁的答案,它确实没有解决您的问题。

检索属性值在功能上等同于调用具有与属性相同的返回类型的函数(一种方法)。在这种情况下,它返回System.Action一个委托实例。委托具有您通常调用的 Invoke 方法。VB.Net 允许您使用delegateName()相当于delegatename.Invoke(). VB.Net 还允许您在调用方法时省略空参数列表,我认为这是导致您对语法有些困惑的原因。

例如:

Sub DoSomething()
End Sub
Run Code Online (Sandbox Code Playgroud)

..可以这样写:

DoSomething
' or 
DoSomething()
Run Code Online (Sandbox Code Playgroud)

为什么这两种调用方法的方式之间的差异是DoSomething相关的?这是因为要让 VB.Net 理解您要在从 Property-Get 函数返回的 Action 实例上使用简写符号,您需要使用后置的 '()' 后跟的第二种形式一秒 '()'。第一个集合结束方法调用,第二个集合告诉 VB 调用 Invoke 方法。请注意,如果该方法需要参数,则包含在 '()' 中的参数列表不能为空。

所以:

DelegateReturnedFromProperty()()
Run Code Online (Sandbox Code Playgroud)

相当于:

DelegateReturnedFromProperty.Invoke
' or
DelegateReturnedFromProperty().Invoke()
Run Code Online (Sandbox Code Playgroud)

这是一种风格偏好,但DelegateReturnedFromProperty()()如果代码由不完全熟悉 VB.Net 调用委托的语法糖的人审查,似乎只是在要求混淆。