현재 클래스 / 메서드 이름을 반환하는 함수가 있습니까? [복제]
이 질문에 이미 답변이 있습니다.
- C # 자체 클래스 이름 가져 오기 9 답변
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);
'program tip' 카테고리의 다른 글
MAMP에 포함 된 MySQL에 구성 파일이 포함되어 있지 않습니까? (0) | 2020.09.07 |
---|---|
xaml wpf의 텍스트 상자에 포커스 설정 (0) | 2020.09.07 |
Numpy 배열의 열을 반복하는 방법은 무엇입니까? (0) | 2020.09.07 |
distutils를 사용하여 설치된 Python 패키지를 어떻게 제거합니까? (0) | 2020.09.06 |
중괄호로 묶인 이니셜 라이저는 언제 사용합니까? (0) | 2020.09.06 |