lundi 28 août 2017

Get method name of a delegate passed as a parameter (Compact Framework)

I have a function that takes a Func as a parameter, invokes it, and writes some results to a log. For logging purposes, it would be nice to be able to be able to access the name of the function that is actually being called when the lambda expression executes. Is there a way to do this in compact framework?

    Private Function tryWithLogging(ByVal moveFunc As Func(Of Boolean), ByVal maxRetries As Integer) As Boolean
        Dim attemptsRemaining As Integer = maxRetries

        While True
            Try
                If moveFunc.Invoke() Then
                    Return True
                Else
                    Dim name as String = '??????
                    WriteToLog(_CLASS_NAME, name, "Failed while moving")

                    If attemptsRemaining > 0 Then
                        'try again
                        attemptsRemaining -= 1
                        Continue While
                    Else
                        'exceeded retries
                        Return False
                    End If
                End If
            Catch ex As Exception
                If attemptsRemaining > 0 Then
                    'try again
                    attemptsRemaining -= 1
                    Continue While
                Else
                    'exceeded retries
                    Return False
                End If
            End Try
        End While
    End Function

Example usage:

tryWithLogging(Function() someXYZMove(x,y,z), 2) 

Here's what I have attempted to retrieve the name:

moveFunc.Method.Name 'returns whatever the compiler decided to name the lambda

New StackTrace().GetFrame(1).GetMethod().Name 'works, but is not available on CF

I have also tried passing an Expression(Of Func(Of Boolean)) instead and getting the name from that, but that is also not available on CF.

Is there any way to retrieve the name of a function being invoked by a lambda within the shackles of compact framework?





Aucun commentaire:

Enregistrer un commentaire