0

我有这个清单:

List<string> x=new List<string>

所以,现在我想在计数增加时做点什么。我试过:

if(x.Count++){
  //do stuff
}

但它没有用。那么我可以尝试什么?

4

1 回答 1

5

你不能像你试图做的那样做。if (x.Count++)没有意义 - 您正在尝试增加计数(这是只读的)。

我将派生并List<T>添加事件。ItemAddedItemRemoved

实际上,那将是重新发明轮子。这样的集合已经存在。请参阅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);
}

参考:

于 2013-11-01T21:45:36.497 回答