我需要确定是否更新了列表(添加/删除了项目)。我需要使用System.Collections.Generic.List<T>
,我不能使用ObservableCollection
(并订阅它的CollectionChanged
事件)。
这是我到目前为止所尝试的内容:
我正在使用Fody.PropertyChanged
而非实施INotifyPropertyChangedEvent
- Fody Property Changed on GitHub
[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
}
有没有更好的方法。如果我做错了,请告诉我,以便我可以改进。
答案 0 :(得分:2)
您可以使用扩展方法:
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;
}
}
}