C#
[C#] CallerMemberName Attribute 사용법
HyoSeong
2021. 6. 30. 16:03
반응형
C#에는 Attribute라는 유용한 친구가 있습니다.
그중 CallerMemberName을 사용하면 이 함수를 호출한 대상에 대한 이름을 인자로 받게 됩니다.
사용법은 다음과 같습니다.
// Program.cs
static void Main(string[] args)
{
SomeFunction(); // output : Main
}
public static void SomeFunction([CallerMemberName] string callerName = null)
{
Console.WriteLine(callerName);
}
한가지 주의할 점은 default value를 지정해 주어야 한다는 점입니다.
CallerMemberName외에도 CallerFilePath, CallerLineNumber도 있습니다.
저는 주로 INotifyPropertyChanged를 구현할 때 CallerMemberName을 사용합니다.
(BindableBase를 일부분 가져와 사용합니다.)
// SomeModel.cs
public class SomeModel : INotifyPropertyChanged
{
private string someString;
public string SomeString
{
get => someString;
set => SetProperty(ref someString, value);
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public void SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
{
storage = value;
OnPropertyChanged(propertyName);
}
}
반응형