[英]How do I check if the count of a list is increasing?
我有這個清單:
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);
}
參考文獻:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.