Qual é a melhor maneira de verificar se System.Collections.Generic.List<T> está atualizado (C# 4.0)?
-
21-12-2019 - |
Pergunta
Preciso identificar se uma lista está atualizada (item adicionado/removido).eu preciso usar System.Collections.Generic.List<T>
, não posso usar ObservableCollection
para isso (e inscreva-se CollectionChanged
evento).
Aqui está o que tentei até agora:
estou usando Fody.PropertyChanged
em vez de implementar INotifyPropertyChangedEvent
- Propriedade Fody alterada no 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 alguma abordagem melhor.Por favor, deixe-me saber se estou fazendo algo errado, para que eu possa melhorar.
Solução
Você pode usar métodos de extensão:
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 extensão em si.
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 em: CC-BY-SA com atribuição
Não afiliado a StackOverflow