system.collections.generic.list が更新されているかどうかを確認する最善の方法は何ですか?
-
21-12-2019 - |
質問
リストが更新されたかどうかを識別する必要があります(アイテムが追加/削除されました)。System.Collections.Generic.List<T>
を使用する必要があります。これにはObservableCollection
を使用できません(そしてそれはCollectionChanged
イベントを購読する)。
これまでに試したものです:
Fody.PropertyChanged
を実装する代わりにINotifyPropertyChangedEvent
を使用しています - fodyプロパティが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
}
.
はより良いアプローチがありますか。私がうまくいっているのかどうか私に知らせてください、それで私は改善することができます。
解決
拡張方法を使用できます。
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