【问题标题】:Get the name of the current method获取当前方法的名称
【发布时间】:2011-01-04 07:20:15
【问题描述】:

这是一个愚蠢的问题,但是是否可以从该方法中获取当前正在执行的方法的名称?

Public Sub SomeMethod()

   Dim methodName as String = System.Reflection.[function to get the current method name here?]

End Sub

谢谢

【问题讨论】:

标签: .net vb.net reflection


【解决方案1】:

【讨论】:

  • 更好的使用基类:System.Reflection.MethodBase.GetCurrentMethod();
  • @marstone - 你能解释一下为什么吗?
  • @PunkyGuy 有人说:“虽然两个调用的效果完全相同,但在实际定义它们的类的子类上调用共享函数通常是个坏主意”。参考:bytes.com/topic/visual-basic-net/answers/…
  • 这在优化的情况下并不总是有效。有时当前的方法会被优化掉。
【解决方案2】:

其他方法与所要求的很接近,但它们不返回 string 值。但这确实:

Dim methodName$ = System.Reflection.MethodBase.GetCurrentMethod().Name

【讨论】:

    【解决方案3】:

    为保证此问题的任何答案在运行时都有效 (System.Reflection.MethodBase.GetCurrentMethod().Name),您需要添加一个属性。据我所知,没有编译器/运行时标志会破坏此方法:

    你试图获取must be marked名称的函数

    • F#[<System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)>]
    • VB:&lt;System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)&gt;

    • C#:[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]

    另外,现在,在 VB、C#(and maybe F# soon) 中有 nameof() 运算符 你的情况是nameof(SomeMethod)(我相信这里的VB和C#的语法是一样的)

    【讨论】:

      【解决方案4】:

      另一种方法是使用 System.​Runtime.​Compiler​Services 命名空间中的 Caller​Member​Name​Attribute 来填充可选参数。比如……

      Private Function GetMethodName(<System.Runtime.CompilerServices.CallerMemberName>
          Optional memberName As String = Nothing) As String
      
          Return memberName
      
      End Function
      

      函数会按照你的预期被调用...

      Public Sub DoSomeWork()
          Dim methodName As String = GetMethodName()
          Console.WriteLine($"Entered {methodName}")
      
          ' Do some work
      End Sub
      

      除了“仅仅”检索方法名称外,该函数还可以利用检索到的方法名称来进一步简化代码。比如……

      Private Sub TraceEnter(
          <System.Runtime.CompilerServices.CallerMemberName>
          Optional memberName As String = Nothing)
      
          Console.WriteLine($"Entered {memberName}")
      
      End Sub
      

      ...可能会这样使用...

      Public Sub DoSomeWork()
          TraceEnter()
      
          ' Do some work
      
      End Sub
      

      CompilerServices 命名空间中的其他属性可以以类似的方式用于检索源文件的完整路径(在编译时)和/或调用的行号。有关示例代码,请参阅 CallerMemberNameAttribute 文档。

      【讨论】:

        【解决方案5】:
        Dim methodName As String = System.Reflection.MethodBase.GetCurrentMethod().Name
        

        【讨论】:

          猜你喜欢
          • 2016-03-13
          • 2010-10-01
          • 2010-09-19
          • 2016-11-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-08-05
          相关资源
          最近更新 更多