我有这个清单:
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);
}
参考: