C# 프로젝트를 하면서 어트리뷰트를 사용하는 경우가 거의 없는데
그나마 가장 유용하게 사용한 것이 바로 이 CallerMemberName이다.
해당 클래스를 통해서 너무나도 쉽게 구현되는 것이 있다.
바로 MVVM 패턴에서 뷰모델의 속성을 Notify 해주는 부분인데
보통 속성의 값이 변경되었을때 변경된 값을 UI에 반영해주기 위해서는
INotifyPropertyChanged 인터페이스를 구현하여 PropertyChanged 이벤트를 호출해줘야한다.
우선 PropertyChanged Event를 호출해주는 Property를 구현해보자.
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _message;
public string Message
{
get
{
return _message;
}
set
{
_message = value;
if (PropertyChanged != null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Message");
}
}
}
}
해당 Message 속성의 set 부분인데 속성하나를 정의하는데 저정도의 코드를 매번 입력해주려면 너무 피곤하다.
그래서 쉽고 빠르게 속성을 구현하기 위해서 아래와 같이 코드를 작성할 수 있다.
public void SetProperty<T>(ref T storage, T value, string propertyName)
{
if(storage?.Equlas(value) == true) return;
storage = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public string Message
{
get => _message;
set => SetProperty(ref _message, value, "Message");
}
여기서 문제는 propertyName을 입력해주는 부분이다. 매속성마다 이름을 다 하드코딩 해줘야한다.
하드코딩의 단점이라면 뭐 참조되는지 알 수 없고 관리도 힘들고 타이핑도 힘들고 여러모로 단점이 많다.
그래서 하드코딩이라는 단점을 없애기 위해 아래와 같이 쓸 수는 있다.
public string Message
{
get => _message;
set => SetProperty(ref _message, value, nameof(Message));
}
이 정도만 해도 잘 쓸 수는 있겠다. 하지만 여기서 한발 더 나아가는게 CallerMemberName 어트리뷰트를 사용하는 것이다.
이번에는 SetProperty 함수를 다시 구현해보자
using System.Runtime.CompilerServices;
protected SetProperty<T>(ref T Storage, T value, [CallerMemberName]string propertyName = null)
{
if (storage?.Equals(value) == true) return;
storage = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
위와 같이 함수를 작성해주면 속성에서 SetProperty 함수를 호출할 시에는 매개변수에 자동으로 속성이름이 대입된다.
그래서 다시 Message 속성을 구현하면
public string Message { get => _message; set => SetProperty(ref _message, value); }
위와 같이 쉽고 빠르게 속성을 구현할 수가 있게된다.
이 정도면 속성 하나 구현하는건 너무나도 쉽다.
여기서 더 해볼 수 있는 것이 있는데 snippet이다. 이 것은.... 나도 아직 생각만해보고 실제 프로젝트에 적용은 안해봤는데 다음에 한번 직접 구현해보고 포스팅해보겠다.
'SW개발 > c#' 카테고리의 다른 글
[C#] SubClass list 생성 (0) | 2023.09.01 |
---|---|
[WPF] Messenger 구현 (MVVM) (0) | 2023.02.17 |
[WPF]WndProc - 윈도우메시지 처리 적용 (0) | 2023.02.14 |
[WPF] 모든 에러 발생시 이벤트 발생시키기 (0) | 2023.02.14 |
[C#] Logger (0) | 2023.01.31 |