简体   繁体   English

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

[英]How do I check if the count of a list is increasing?

I have this list: 我有这个清单:

List<string> x=new List<string>

So, now I want to do something when the count is being increased. 所以,现在我想在增加计数时做点什么。 I tried: 我试过了:

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

But it did not work. 但这没有用。 So what can I try? 那我该怎么办?

You can't do this like you're trying to do. 您无法像尝试那样去做。 if (x.Count++) makes no sense - you're attempting to increment the count (which is read-only). if (x.Count++)没有意义-您正在尝试增加计数(只读)。

I would derive from List<T> and add ItemAdded and ItemRemoved events. 我将从List<T>派生并添加ItemAddedItemRemoved事件。

Actually, that would be re-inventing the wheel. 实际上,那将是在重新发明轮子。 Such a collection already exists. 这样的集合已经存在。 See ObservableCollection<T> , which raises a CollectionChanged event. 请参见ObservableCollection<T> ,它引发一个CollectionChanged事件。 The NotifyCollectionChangedEventArgs tells you what changed. NotifyCollectionChangedEventArgs告诉您更改了什么。

Example (not tested): 示例(未经测试):

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);
}

References: 参考文献:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM