system.collections.generic.list が更新されているかどうかを確認する最善の方法は何ですか?

StackOverflow https://stackoverflow.com//questions/25055270

質問

リストが更新されたかどうかを識別する必要があります(アイテムが追加/削除されました)。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;
        }
    }
}
.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top