ما هي أفضل طريقة للتحقق من تحديث System.Collections.Generic.List<T> (C# 4.0)؟
-
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