如何检查列表的数量是否增加?

时间:2013-11-01 21:43:59

标签: c#

我有这个清单:

List<string> x=new List<string>

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

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

但它没有用。那我该怎么办呢?

1 个答案:

答案 0 :(得分: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);
}

参考文献: