Using GetCurrentMethod in (supposedly) high-performance code

前端 未结 3 1489
时光取名叫无心
时光取名叫无心 2021-01-18 14:03

For logging purposes, some methods in our application include the following line:

Dim Log As ILog = GetLog(Reflection.MethodBase.GetCurrentMethod().Declaring         


        
3条回答
  •  春和景丽
    2021-01-18 14:41

    Does Me.GetType() return the as GetCurrentMethod().DeclaringType?

    It depends. Me.GetType will always return the actual type of an object. GetCurrentMethod().DeclaringType will return the type in which the method was declared. These values can be different in inheritance scenarios.

    Consider the following

    Class C1
      Public Sub Foo() 
        ..
      End Sub
    End Class
    Class C2 
      Inherits C1
      ..
    End Class
    

    Inside method Foo the two expressions would be equal if you were dealing with an instance of C1. But if it was C2 they would be different.

    Does Me.GetType() do anything differently from GetCurrentMethod().DeclaringType

    Yes these are very different functions. Me.GetType determines the runtime type of the current instance of the class. GetCurrentMethod.DeclaringType determines in what type was this method declared.

    Should I not even be worried about this at all?

    If this is a performance critical scenario then yes you make sure you profile APIs you do not understand. Especially those that appear to involve reflection. But only a profiler will tell you which is definitively faster. My money is on Me.GetType though.

提交回复
热议问题