2

当我还没有声明实例时,我可以创建一个指向实例函数的指针吗?现在我正在使用反射来调用我的方法,但似乎使用某种委托可能会更容易。我就是想不通。我将调用的方法将始终返回相同的类型并且没有参数。

这是一些示例代码来说明我正在尝试做的事情:

Private Shared Function A() As Object

    Return Lauch(????) ' should call FunctionA of the instance (undeclared here)

End Function


Private Shared Function B() As Object

    Return Lauch(????) ' should call FunctionB of the instance (undeclared here)

End Function


Private Shared Function Lauch(Of T)(ByVal instanceFunc As Func(Of T)) As Object

    ' long and repetitive operations that I don't want to repeat in function A and B

    Dim myInstance As New MyClass()

    Return myInstance.instanceFunc()

End Function

现在我正在做类似以下的事情并且它有效,但我觉得应该有更好的方法:

Private Shared Function A() As Object

    Return Lauch("FunctionA")

End Function


Private Shared Function B() As Object

    Return Lauch("FunctionB")

End Function


Private Shared Function Lauch(ByVal instanceFunc As String) As Object

    ' long and repetitive operations that I don't want to repeat in function A and B

    Dim myInstance As New MyClass()

    Return myInstance.GetType().GetMethod(instanceFunc).Invoke(myInstance, Nothing))

End Function
4

1 回答 1

1

那这个呢?

Private Shared Function A() As Object
    Return Lauch(Function(x) x.A())
End Function


Private Shared Function Lauch(ByVal instanceFunc As Func(Of CustomClass, Object)) As Object
    ' long and repetitive operations
    Dim myInstance As New CustomClass()
    Return instanceFunc(myInstance)
End Function

基本上,您定义确定函数结果的Lauch函数。这是一个接受 aCustomClass并返回a 的函数Object。在A方法中定义此函数以返回实例A函数的结果。

于 2013-02-12T23:50:17.030 回答