一直在对 ObservableCollection 实现进行一些研究,我发现了一些我无法理解的代码。这是.Net Reflector反编译的代码片段:
[NonSerialized]
private NotifyCollectionChangedEventHandler CollectionChanged;
[NonSerialized]
private PropertyChangedEventHandler PropertyChanged;
event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
{
add
{
this.PropertyChanged += value;
}
remove
{
this.PropertyChanged -= value;
}
}
public virtual event NotifyCollectionChangedEventHandler CollectionChanged
{
add
{
NotifyCollectionChangedEventHandler changedEventHandler = this.CollectionChanged;
NotifyCollectionChangedEventHandler comparand;
do
{
comparand = changedEventHandler;
changedEventHandler = Interlocked.CompareExchange<NotifyCollectionChangedEventHandler>(ref this.CollectionChanged, comparand + value, comparand);
}
while (changedEventHandler != comparand);
}
remove
{
NotifyCollectionChangedEventHandler changedEventHandler = this.CollectionChanged;
NotifyCollectionChangedEventHandler comparand;
do
{
comparand = changedEventHandler;
changedEventHandler = Interlocked.CompareExchange<NotifyCollectionChangedEventHandler>(ref this.CollectionChanged, comparand - value, comparand);
}
while (changedEventHandler != comparand);
}
}
protected virtual event PropertyChangedEventHandler PropertyChanged
{
add
{
PropertyChangedEventHandler changedEventHandler = this.PropertyChanged;
PropertyChangedEventHandler comparand;
do
{
comparand = changedEventHandler;
changedEventHandler = Interlocked.CompareExchange<PropertyChangedEventHandler>(ref this.PropertyChanged, comparand + value, comparand);
}
while (changedEventHandler != comparand);
}
remove
{
PropertyChangedEventHandler changedEventHandler = this.PropertyChanged;
PropertyChangedEventHandler comparand;
do
{
comparand = changedEventHandler;
changedEventHandler = Interlocked.CompareExchange<PropertyChangedEventHandler>(ref this.PropertyChanged, comparand - value, comparand);
}
while (changedEventHandler != comparand);
}
}
我无法理解的是为什么 PropertyChanged 有两个(公共和私有)实现,但 CollectonChanged 只有一个(受保护)?在 do-while 循环中委托算术的目的是什么?为什么不像 PropertyChanged 的私有实现那样只是“this.Property += value”?