programing

현재 메서드의 이름을 가져옵니다.

nasanasas 2020. 11. 26. 08:27
반응형

현재 메서드의 이름을 가져옵니다.


이것은 일종의 어리석은 질문이지만 해당 메서드 내에서 현재 실행중인 메서드의 이름을 가져올 수 있습니까?

Public Sub SomeMethod()

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

End Sub

감사


System.Reflection.MethodInfo.GetCurrentMethod();


다른 메서드는 요청 된 것과 비슷하지만 문자열 값을 반환하지 않습니다 . 그러나 이것은 :

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

이 질문에 제시된 답변이 System.Reflection.MethodBase.GetCurrentMethod().Name런타임에 실제로 작동하도록 보장하려면 ( ) 속성을 추가해야합니다. 이 메서드를 중단하는 컴파일러 / 런타임 플래그는 없습니다.

이름을 얻으려는 함수는 표시되어야합니다.

  • 에프# [<System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)>]
  • VB : <System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)>

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

또한 요즘에는 nameof()VB, C # ( 및 아마도 F # 곧 )에 연산자 가 있습니다. nameof(SomeMethod)(여기서 구문은 VB와 C #에 대해 동일하다고 생각합니다)


또 다른 접근 방식은 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 문서를 참조하십시오.


Dim methodName As String = System.Reflection.MethodBase.GetCurrentMethod().Name

참고 URL : https://stackoverflow.com/questions/2051217/get-the-name-of-the-current-method

반응형