.Net实例函数指针

时间:2013-02-12 23:29:44

标签: .net vb.net reflection delegates

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

以下是一些示例代码,用于说明我正在尝试做的事情:

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

1 个答案:

答案 0 :(得分: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函数结果的函数。这是一个需要CustomClass并返回Object的函数。在A方法中,您定义此函数以返回实例的A函数的结果。