我有這樣的名單:如何檢查列表的數量是否增加?
List<string> x=new List<string>
所以,現在我想要做的事當計數正在增加。我試過了:
if(x.Count++){
//do stuff
}
但它沒有奏效。那麼,我可以嘗試什麼?
我有這樣的名單:如何檢查列表的數量是否增加?
List<string> x=new List<string>
所以,現在我想要做的事當計數正在增加。我試過了:
if(x.Count++){
//do stuff
}
但它沒有奏效。那麼,我可以嘗試什麼?
你不能這樣做,就像你想要做的那樣。 if (x.Count++)
沒有任何意義 - 您正在嘗試增量計數(它是隻讀的)。
我會從List<T>
派生並添加ItemAdded
和ItemRemoved
事件。
其實,這將重新發明車輪。這樣一個集合已經存在。見ObservableCollection<T>
,這引發了一個CollectionChanged
事件。 NotifyCollectionChangedEventArgs
告訴你什麼改變。
實施例(未測試):
void ChangeHandler(object sender, NotifyCollectionChangedEventArgs e) {
switch (e.Action) {
case NotifyCollectionChangedAction.Add:
// One or more items were added to the collection.
break;
case NotifyCollectionChangedAction.Move:
// One or more items were moved within the collection.
break;
case NotifyCollectionChangedAction.Remove:
// One or more items were removed from the collection.
break;
case NotifyCollectionChangedAction.Replace:
// One or more items were replaced in the collection.
break;
case NotifyCollectionChangedAction.Reset:
// The content of the collection changed dramatically.
break;
}
// The other properties of e tell you where in the list
// the change took place, and what was affected.
}
void test() {
var myList = ObservableCollection<int>();
myList.CollectionChanged += ChangeHandler;
myList.Add(4);
}
參考文獻:
你能澄清嗎? – stackptr
看起來像解決方案。您必須檢查列表的初始大小和當前大小,以確定是否添加或刪除了某些內容;合適的事件似乎並沒有區分兩者。 –
'List.Add()'方法和其他相關的方法是非虛擬的,所以你不能真正做到這一點。你將不得不重新實現它。 –
隧道所有添加元素的波谷其激活的事件自己委託方法。 –
有什麼更簡單的嗎? – stackptr
所有的代碼都不是那麼廣泛;它聽起來比現在更多。你必須利用不直接可用的事件處理程序,所以你必須解決這個問題。 –