program tip

현재 클래스 / 메서드 이름을 반환하는 함수가 있습니까?

radiobox 2020. 9. 7. 07:58
반응형

현재 클래스 / 메서드 이름을 반환하는 함수가 있습니까? [복제]


이 질문에 이미 답변이 있습니다.

C #에서 현재 클래스 / 메서드 이름을 반환하는 함수가 있습니까?


현재 클래스 이름 :

this.GetType().Name;

현재 메소드 이름 :

using System.Reflection;

// ...

MethodBase.GetCurrentMethod().Name;

로깅 목적으로 이것을 사용하고 있기 때문에 현재 스택 추적 을 얻는 데 관심이있을 수도 있습니다 .


System.Reflection.MethodBase.GetCurrentMethod()


System.Reflection.MethodBase.GetCurrentMethod().DeclaringType

위의 예제를이 작업 예제 코드로 약간 변경했습니다.

public class MethodLogger : IDisposable
{
    public MethodLogger(MethodBase methodBase)
    {
        m_methodName = methodBase.DeclaringType.Name + "." + methodBase.Name;
        Console.WriteLine("{0} enter", m_methodName);
    }

    public void Dispose()
    {
        Console.WriteLine("{0} leave", m_methodName);
    }
    private string m_methodName;
}

class Program
{
    void FooBar()
    {
        using (new MethodLogger(MethodBase.GetCurrentMethod()))
        {
            // Write your stuff here
        }
    }
}

산출:

Program.FooBar enter
Program.FooBar leave

예! MethodBase 클래스의 정적 GetCurrentMethod는 호출 코드를 검사하여 생성자인지 일반 메서드인지 확인하고 MethodInfo 또는 ConstructorInfo를 반환합니다.

이 네임 스페이스는 리플렉션 API의 일부이므로 기본적으로 런타임에서 볼 수있는 모든 것을 사용할 수 있습니다.

Here you will find an exhaustive description of the API:

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

If you don't feel like looking through that entire library here is an example I cooked up:

namespace Canvas
{
  class Program
  {
    static void Main(string[] args)
    {
        Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod());
        DiscreteMathOperations viola = new DiscreteMathOperations();
        int resultOfSummation = 0;
        resultOfSummation = viola.ConsecutiveIntegerSummation(1, 100);
        Console.WriteLine(resultOfSummation);
    }
}

public class DiscreteMathOperations
{
    public int ConsecutiveIntegerSummation(int startingNumber, int endingNumber)
    {
        Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod());
        int result = 0;
        result = (startingNumber * (endingNumber + 1)) / 2;
        return result;
    }
}    
}

The output of this code will be:

Void Main<System.String[]> // Call to GetCurrentMethod() from Main.
Int32 ConsecutiveIntegerSummation<Int32, Int32> //Call from summation method.
50 // Result of summation.

Hope I helped you!

JAL


You can get the current class name, but I can't think of anyway to get the current method name. Though, the names of methods for the current can be obtained.

string className = this.GetType().FullName;
System.Reflection.MethodInfo[] methods = this.GetType().GetMethods();
foreach (var method in methods)
    Console.WriteLine(method.Name);

참고URL : https://stackoverflow.com/questions/5387073/is-there-a-function-that-returns-the-current-class-method-name

반응형