.NET 有ObservableCollection<T>,但它用于观察存储对象和集合本身发生的变化。您的集合没有改变(假设我理解正确) - 如果某些属性值与之前的迭代不同,您只想在循环期间得到通知。
就可重用代码而言,可能会为您指明正确的方向:
public class PropertyWatcher<TSource>
{
// initialization code omitted
private Dictionary<string, object> previousValues;
private Dictionary<string, Func<TSource, object>> selectors;
public void RegisterWatcher<TSource>(Func<TSource, object> propertySelector,
string propertyName)
{
this.selectors.Add(propertyName, propertySelector);
this.previousValues.Add(propertyName, null);
}
public void NotifyIfDifferent<TObject, TPropertyType>(TSource currentItem)
{
foreach (var key in this.selectors.Keys)
{
var selector = this.selectors[key];
var currentValue = selector(currentItem);
if (!currentValue.Equals(this.previousValues[key]))
{
// raise notification, event; antyhing to your liking
}
this.previousValues[key] = currentValue;
}
}
}
并且,假设我们正在处理您提到的 P1 和 P2 属性,用法如下所示:
var list = new List<SomeObject>(); // list of items you intend to watch
var watcher = new PropertyWatcher<SomeObject>();
watcher.RegisterWatcher((SomeObject o) => o.P1, "P1");
watcher.RegisterWatcher((SomeObject o) => o.P2, "P2");
foreach (var item in list)
{
watcher.NotifyIfDifferent(item);
}
这绝不是完整的解决方案。它应该在涉及简单值时起作用(因此.Equals 可以轻松处理比较)。当然,您仍然需要向 PropertyWatcher 类添加一些事件,并且可能会在这里和那里调整它 - 但我认为总体思路相当容易掌握。
不过,对于更高级的场景,我想您必须采用更通用的方法。