Qual è il modo migliore per controllare se system.collections.generic.list è aggiornato (c # 4.0)?
-
21-12-2019 - |
Domanda
Devo identificare se viene aggiornato un elenco (articolo aggiunto / rimosso).Devo usare System.Collections.Generic.List<T>
, non posso utilizzare ObservableCollection
per questo (e iscriversi all'evento CollectionChanged
).
Ecco cosa ho provato finora:
Sto usando Fody.PropertyChanged
invece di implementare INotifyPropertyChangedEvent
- Proprietà Fody cambiata su 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
}
.
C'è un approccio migliore.Per favore fatemi sapere se sto facendo qualcosa di sbagliato, in modo che io possa migliorare.
Soluzione
È possibile utilizzare metodi di estensione:
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");
.
Metodo di estensione stesso.
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;
}
}
}
. Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow