System.Collections.Generic.List 가 업데이트되는지 확인하는 가장 좋은 방법은 무엇입니까?
-
21-12-2019 - |
문제
목록이 업데이트되면 식별해야합니다 (항목 추가 / 제거).System.Collections.Generic.List<T>
를 사용해야합니다. ObservableCollection
를 사용할 수 없습니다 (및 CollectionChanged
이벤트에 가입).
여기에서 내가 시도한 것입니다 :
Fody.PropertyChanged
- 에서 변경된 Fody 속성
INotifyPropertyChangedEvent
를 사용하고 있습니다.
[AlsoNotifyFor("ListCounter")]
public List<MyClass> MyProperty
{get;set;}
public int ListCounter {get {return MyProperty.Count;}}
//This method will be invoked when ListCounter value is changed
private void OnListCounterChanged()
{
//Some opertaion here
}
.
더 나은 접근이 있습니다.내가 뭔가 잘못하고 있는지 알려 주시기 바랍니다. 그래서 내가 개선 할 수 있습니다.
해결책
확장 방법을 사용할 수 있습니다.
var items = new List<int>();
const int item = 3;
Console.WriteLine(
items.AddEvent(
item,
() => Console.WriteLine("Before add"),
() => Console.WriteLine("After add")
)
? "Item was added successfully"
: "Failed to add item");
.
확장 방법 자체.
public static class Extensions
{
public static bool AddEvent<T>(this List<T> items, T item, Action pre, Action post)
{
try
{
pre();
items.Add(item);
post();
return true;
}
catch (Exception)
{
return false;
}
}
}
. 제휴하지 않습니다 StackOverflow