[C#] 호출자 정보 알아내기
메서드 호출시 메서드 안에서 어디에서 호출된 것인지 알고 싶을때가 있다
특히 로그 남길 때 유용하게 쓸수 있다.
아래 코드 처럼 메서드 인자로 [CallerMemberName], [CallerFilePath], [CallerLineNumber] 를 선언해 주면 알아서 내용이 들어가게된다.
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Windows.Forms;
namespace CompilerServicesTest
{
public partial class TestForm : Form
{
public TestForm()
{
InitializeComponent();
CallMethod();
}
private void CallMethod()
{
WriteLog("CompilerServices Test!!");
}
private void WriteLog(string message,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0)
{
Trace.WriteLine("message: " + message);
Trace.WriteLine("member name: " + memberName);
Trace.WriteLine("source file path: " + sourceFilePath);
Trace.WriteLine("source line number: " + sourceLineNumber);
}
}
}
참고
https://docs.microsoft.com/ko-kr/dotnet/csharp/language-reference/attributes/caller-information