我有一个计时器滴答事件:
private void timer2_Tick(object sender, EventArgs e)
{
combindedString = string.Join(Environment.NewLine, ListsExtractions.myList);
richTextBox1.SelectAll();
richTextBox1.SelectionAlignment = HorizontalAlignment.Right;
richTextBox1.Text = combindedString;
}
定时器设置为 50000 并且时间一直在一遍又一遍地运行。
现在 List<string> myList
当我运行我的程序时,例如有 3 个项目:
Index 0: Hello world
Index 1: 24/7/2014 21:00
Index 2: http://test.com
50 秒后有两个选项:列表未更改或已更改/更长。 如果没有改变,什么也不做,但如果改变了,获取最新添加的项目。例如,如果列表现在已更改为...
Index 0: This is the latest item added in index 0
Index 1: 24/7/2014 22:00
Index 2: http://www.google.com
Index 3: ""
Index 4: Hello world
Index 5: 24/7/2014 21:00
Index 6: http://test.com
...然后我需要做另外两个 Action :
第一次运行程序时,检查最近的项目(在本例中为
Index 0
处的字符串)是否包含两个单词/字符串。如果是,那就做点什么,否则什么都不做。
但是,如果它确实包含单词/字符串并且我们做“做某事”,则只在 50 秒后做一次;即使单词/字符串再次出现在索引 0 中,也不要再这样做。如果 List 在 50 秒后发生变化并且在
Index 0
中这个单词/字符串存在,50 秒后只做一次。如果列表没有改变,即使单词/字符串仍然存在于索引 0 中,也不要再做一次。if (rlines[0].Contains("צבע אדום") || rlines[0].Contains("אזעקה")) { timer3.Start(); }
我要开始timer3
仅当其中一个单词/字符串存在于索引 0 中时。
如果 50 秒后没有任何变化,请不要开始 timer3
再次。
只有在 50 秒或更晚之后列表发生变化并且其中一个单词/字符串再次出现在索引 0 中时才再次启动计时器 3。
最佳答案
通用 List<T>
类不支持列表更改通知。
您要找的是 ObservableCollection<T>
.
它有一个 CollectionChanged
在修改集合时触发。
您可以通过以下方式使用它:
using System.Collections.ObjectModel;
ObservableCollection<string> myList;
//The cnstructor
public MyClassname()
{
this.myList = new ObservableCollection<string>();
this.myList.CollectionChanged += myList_CollectionChanged;
}
void myList_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
//list changed - an item was added.
if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
{
//Do what ever you want to do when an item is added here...
//the new items are available in e.NewItems
}
}
关于c# - 我如何检测 List<string> 是否已更改?最后添加的项目是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24925037/