your programing

메서드 내에서 호출 메서드 이름 검색

lovepro 2020. 12. 27. 20:26
반응형

메서드 내에서 호출 메서드 이름 검색


중복 가능성 :
현재 메서드를 호출 한 메서드를 어떻게 찾을 수 있습니까?

개체 내의 여러 위치에서 호출되는 개체에 메서드가 있습니다. 이 인기있는 메서드를 호출 한 메서드의 이름을 빠르고 쉽게 얻을 수있는 방법이 있습니까?

의사 코드 예 :

public Main()
{
     PopularMethod();
}

public ButtonClick(object sender, EventArgs e)
{
     PopularMethod();
}

public Button2Click(object sender, EventArgs e)
{
     PopularMethod();
}

public void PopularMethod()
{
     //Get calling method name
}

에서 호출 된 경우 PopularMethod()의 값을 보고 싶습니다 ... 에서 호출 된 경우 " " 을 (를)보고 싶습니다.MainMainButtonClickPopularMethod()ButtonClick

나는을보고 System.Reflection.MethodBase.GetCurrentMethod()있었지만 호출 방법을 얻지 못할 것입니다. StackTrace클래스를 살펴 봤지만 메서드가 호출 될 때마다 전체 스택 추적을 실행하는 것을 좋아하지는 않았습니다.


스택을 추적하지 않고는 할 수 없다고 생각합니다. 그러나 그렇게하는 것은 매우 간단합니다.

StackTrace stackTrace = new StackTrace();
MethodBase methodBase = stackTrace.GetFrame(1).GetMethod();
Console.WriteLine(methodBase.Name); // e.g.

그러나 나는 당신이 정말로 멈추고 이것이 필요한지 스스로에게 물어봐야한다고 생각합니다.


.NET 4.5 / C # 5에서는 간단합니다.

public void PopularMethod([CallerMemberName] string caller = null)
{
     // look at caller
}

컴파일러는 자동으로 발신자의 이름을 추가; 그래서:

void Foo() {
    PopularMethod();
}

전달됩니다 "Foo".


이것은 실제로 정말 간단합니다.

public void PopularMethod()
{
    var currentMethod = System.Reflection.MethodInfo
        .GetCurrentMethod(); // as MethodBase
}

그러나 조심하십시오. 메서드를 인라인하는 것이 효과가 있는지에 대해서는 약간 회의적입니다. 이렇게하면 JIT 컴파일러가 방해가되지 않도록 할 수 있습니다.

[System.Runtime.CompilerServices.MethodImpl(
 System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public void PopularMethod()
{
    var currentMethod = System.Reflection.MethodInfo
        .GetCurrentMethod();
}

호출 방법을 얻으려면 :

[System.Runtime.CompilerServices.MethodImpl(
 System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
public void PopularMethod()
{
    // 1 == skip frames, false = no file info
    var callingMethod = new System.Diagnostics.StackTrace(1, false)
         .GetFrame(0).GetMethod();
}

매개 변수를 전달하기 만하면됩니다.

public void PopularMethod(object sender)
{

}

IMO : 이벤트에 충분하다면 이것으로 충분해야합니다.


I have often found my self wanting to do this, but have always ending up refactoring the design of my system so I don't get this "Tail wagging the dog" anti-pattern. The result has always been a more robust architecture.


While you can most definitley trace the Stack and figure it out that way, I would urge you to rethink your design. If your method needs to know about some sort of "state", I would say just create an enum or something, and take that as a Parameter to your PopularMethod(). Something along those lines. Based on what you're posting, tracing the stack would be overkill IMO.


I think you do need to use the StackTrace class and then StackFrame.GetMethod() on the next frame.

This seems like a strange thing to use Reflection for though. If you are defining PopularMethod, can't go define a parameter or something to pass the information you really want. (Or put in on a base class or something...)

ReferenceURL : https://stackoverflow.com/questions/615940/retrieving-the-calling-method-name-from-within-a-method

반응형