检查 System.Collections.Generic.List<T> 是否已更新的最佳方法是什么(C# 4.0)?
-
21-12-2019 - |
题
我需要确定列表是否已更新(添加/删除项目)。我需要使用 System.Collections.Generic.List<T>
, ,我不能使用 ObservableCollection
为此(并订阅它的 CollectionChanged
事件)。
这是我到目前为止所尝试过的:
我在用 Fody.PropertyChanged
而不是实施 INotifyPropertyChangedEvent
- GitHub 上的 Fody 属性已更改
[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