Programing

코드에서 현재 메소드의 이름을 얻는 방법

lottogame 2020. 3. 2. 13:02
반응형

코드에서 현재 메소드의 이름을 얻는 방법


네가 할 수 있다는 걸 알아

this.GetType().FullName

얻기 위해

My.Current.Class

하지만 내가 무엇을 얻을 수

My.Current.Class.CurrentMethod

using System.Diagnostics;
...

var st = new StackTrace();
var sf = st.GetFrame(0);

var currentMethodName = sf.GetMethod();

또는 도우미 방법을 사용하려면 다음을 수행하십시오.

[MethodImpl(MethodImplOptions.NoInlining)]
public string GetCurrentMethod()
{
    var st = new StackTrace();
    var sf = st.GetFrame(1);

    return sf.GetMethod().Name;
}

크레딧이 @stusmith로 업데이트되었습니다.


System.Reflection.MethodBase.GetCurrentMethod().Name메소드 내에서 호출 하십시오.


반사에는 나무의 숲을 숨기는 요령이 있습니다. 현재 메소드 이름을 정확하고 빠르게 얻는 데 문제가 없습니다.

void MyMethod() {
  string currentMethodName = "MyMethod";
  //etc...
}

리팩토링 도구가 자동으로 수정하지는 않습니다.

리플렉션 사용의 (상당한) 비용에 완전히 신경 쓰지 않으면이 도우미 방법이 유용해야합니다.

using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Reflection;
//...

[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetMyMethodName() {
  var st = new StackTrace(new StackFrame(1));
  return st.GetFrame(0).GetMethod().Name;
} 

업데이트 : C # 버전 5 및 .NET 4.5에는 이러한 일반적인 요구에 대한 황금 솔루션이 있습니다. [CallerMemberName] 특성 을 사용하여 컴파일러가 문자열 인수에서 호출 메서드 이름을 자동 생성하도록 할 수 있습니다 . 다른 유용한 속성은 [CallerFilePath]로, 컴파일러가 소스 코드 파일 경로를 생성하고 [CallerLineNumber]는 호출 한 명령문의 소스 코드 파일에서 행 번호를 가져옵니다.


업데이트 2 : 대답의 맨 위에 제안 된 구문은 멋진 리팩토링 도구없이 C # 버전 6에서 작동하도록 만들 수 있습니다.

string currentMethodName = nameof(MyMethod);

이름을 얻는 가장 좋은 방법은 다음과 같습니다.

 this.GetType().FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name;

또는 이것을 시도하십시오

string method = string.Format("{0}.{1}", MethodBase.GetCurrentMethod().DeclaringType.FullName, MethodBase.GetCurrentMethod().Name);   

작동하지 않습니까?

System.Reflection.MethodBase.GetCurrentMethod()

현재 실행중인 메서드를 나타내는 MethodBase 개체를 반환합니다.

네임 스페이스 : System.Reflection

어셈블리 : mscorlib (mscorlib.dll에 있음)

http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.getcurrentmethod.aspx


MethodBase.GetCurrentMethod()JIT 컴파일러가 사용 되는 메소드를 인라인하지 못하게하는 것을 사용할 수도 있습니다 .


최신 정보:

이 메소드에는 StackCrawlMark내가 이해 한 것부터 현재 메소드를 인라인해서는 안되는 JIT 컴파일러에 지정 하는 특수 열거 포함 됩니다.

이것은 SSCLI에있는 열거와 관련된 의견에 대한 나의 해석입니다. 주석은 다음과 같습니다.

// declaring a local var of this enum type and passing it by ref into a function 
// that needs to do a stack crawl will both prevent inlining of the calle and 
// pass an ESP point to stack crawl to
// 
// Declaring these in EH clauses is illegal; 
// they must declared in the main method body

그럼 System.Reflection.MethodBase.GetCurrentMethod().Name그냥 추가 정보가없는 메소드 이름을 표시합니다 원인 '아주 좋은 선택이 아니다.

string MyMethod(string str)위의 속성 처럼 MyMethod거의 적절하지 않은 것을 반환 합니다.

System.Reflection.MethodBase.GetCurrentMethod().ToString()전체 메소드 서명을 반환하는 것이 좋습니다 .


이것을 확인하십시오 : http://www.codeproject.com/KB/dotnet/MethodName.aspx

참고 URL : https://stackoverflow.com/questions/2652460/how-to-get-the-name-of-the-current-method-from-code



반응형