2009-11-23 29 views
1

我想在我定義的ArrayList上執行RemoveAt(i)方法時觸發一個進程。 可以這樣做嗎?怎麼樣?如何將事件處理程序與「組方法」關聯?

感謝,

阿薩夫。

+0

我編輯了我的答案,包括一個例子。如果你不希望使用ObservableCollection所帶來的一切,我認爲這是一個更好的方法。 –

回答

2

那麼用ObservableCollection代替ArrayList呢?它附帶WPF,但我相信如果您使用.net 3.5,則可以毫無問題地使用它。 ObservableCollection實現了INotifyCollectionChanged,因此您可以訪問CollectionChanged事件。您還可以創建自己的集合,實現ICollection和IEnumerable,將ArrayList添加爲字段並在您自己的添加和刪除方法中引發事件。檢出the solution provided by this guy

這裏是你如何能實現你想要的一個片段:

public class MyArrayList : IList, ICollection, IEnumerable, ICloneable 
{ 
    private ArrayList arrayList = new ArrayList(); 

    public event System.EventHandler RemovedItem; 

    public void RemoveAt(int index) 
    { 
     this.arrayList.RemoveAt(item); 
     if (RemovedItem != null) { 
      RemovedItem(this, new EventArgs()); 
     } 
    } 

    // implement required interface members... 
} 
0

你會需要繼承數組列表和覆蓋的方法,爲了這個工作。在.Net 3.5中,有一個「ObservableCollection」類,它實現了一個CollectionChanged事件,如果您不限制使用ArrayList,則可以使用該事件。 ObservableCollection還實現了ICollection和IEnumerable,因此您應該可以將它交換爲ArrayList。

+0

我嘗試了子類化和重寫,但後來因爲RemoveAt是一個'組方法'而出現錯誤... – Asaf

相關問題