¿Cuál es la mejor manera de comprobar si System.Collections.Generic.List<T> está actualizado (C# 4.0)?

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

Pregunta

Necesito identificar si una lista está actualizada (elemento agregado/eliminado).necesito usar System.Collections.Generic.List<T>, No puedo usar ObservableCollection para esto (y suscríbete a su CollectionChanged evento).

Esto es lo que he probado hasta ahora:

estoy usando Fody.PropertyChanged en lugar de implementar INotifyPropertyChangedEvent - Propiedad de Fody cambiada en 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
}

¿Existe algún enfoque mejor?Por favor, avíseme si estoy haciendo algo mal para poder mejorar.

¿Fue útil?

Solución

Puede usar métodos de extensión:

    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");

Método de extensión en sí.

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;
        }
    }
}

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top