개발/기본) 기본기
C#)CallerFilePath : 호출자 정보 확인
테샤르
2023. 12. 18. 09:39
CallerFilePath : 호출자 정보 확인
CallerFilePath은 C# 5.0이상에서 사용하는 Attribute로 현재 멤버, 혹은 메소드가 포함된 경로를 제공한다.
주로 사용하는 경우는 로깅이나 디버깅같은 자신의 위치(경로)를 파악할때 사용한다.
반응형
< 예시 >
로그 파일 확인하는 예제
using System;
using System.Runtime.CompilerServices;
class Logger
{
public static void LogFilePath([CallerFilePath] string filePath = "")
{
Console.WriteLine("File Path: " + filePath);
}
public static void Main()
{
LogFilePath();
}
}
< 예시 >
파일 경로에 따른 다른 동작하는 예제
using System;
using System.Runtime.CompilerServices;
class FileProcessor
{
public static void ProcessFile(string filePath, [CallerFilePath] string callerPath = "")
{
string fileName = System.IO.Path.GetFileName(filePath);
string callerName = System.IO.Path.GetFileName(callerPath);
if (callerName.Equals("Program.cs", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine($"Processing {fileName} from Program.");
}
else
{
Console.WriteLine($"Processing {fileName} from an unknown source.");
}
}
}
class Program
{
static void Main()
{
string filePath = "example.txt";
FileProcessor.ProcessFile(filePath);
}
}
Microsoft c# 컴파일러에서 해석하는 특성을 사용하여 호출자 정보 확인 : [링크]
C# 컴파일러에서 해석하는 특성: 호출자 정보 추적 - C#
이 특성은 멤버를 호출하는 코드에 대한 정보를 생성하도록 컴파일러에 지시합니다. CallerFilePath, CallerLineNumber, CallerMemberName 및 CallerArgumentExpression을 사용하여 자세한 추적 정보를 제공합니다.
learn.microsoft.com
★☆☆☆☆
반응형