【发布时间】:2018-02-06 06:54:14
【问题描述】:
我有一个函数,它将 Func 作为参数,调用它并输出一些结果。出于日志记录的目的,如果能够访问 lambda 表达式执行时实际调用的函数的名称,那就太好了。有没有办法在紧凑的框架中做到这一点?
Private Function tryWithLogging(ByVal moveFunc As Func(Of Boolean)) As Boolean
Try
moveFunc.Invoke()
Dim nameOfMethod as String = '??????
Console.WriteLine("Invoked " & nameOfMethod)
Catch ex As Exception
End Try
End Function
示例用法:
tryWithLogging(Function() myFunction([arbitrary params])
'desired output: "Invoked myFunction"
这是我尝试检索名称的内容:
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
我也尝试传递 Expression(Of Func(Of Boolean)) 并从中获取名称,但 System.Linq.Expressions 在 CF 上也不可用。
有什么方法可以在紧凑框架 3.5 的桎梏中检索由 lambda 调用的函数的名称?
【问题讨论】:
-
@L.B 也许我误解了你的链接,但我认为
CallerMemberName不会帮助我。我想要在 lambda 中调用的方法 being 的名称,而不是执行调用的函数的名称。
标签: c# reflection lambda delegates compact-framework