WF中DependencyObject和DependencyProperty的实现
DependencyProperty的Register和RegisterAttached方法,将DependencyProperty存在IDictionary中完成注册,确保相同name的DependencyProperty在一个ownerType类型中只能有一个。
DependencyObject的GetValue和SetValue的值存在IDictionary中。并预留了GetValueOverride 和SetValueOverride的处理。
用Reflector看了一下源码,下面是源码的片段
[Serializable]
public sealed class DependencyProperty : ISerializable
{
private static IDictionary<int, DependencyProperty> dependencyProperties;
{
return ValidateAndRegister(name, propertyType, ownerType, null, null, true);
}
{
return ValidateAndRegister(name, propertyType, ownerType, null, null, false);
}
//Register和RegisterAttached调用ValidateAndRegister完成注册
private static DependencyProperty ValidateAndRegister(string name, Type propertyType, Type ownerType, PropertyMetadata defaultMetadata, Type validatorType, bool isRegistered)
{
// Check ...
// ...
DependencyProperty property = new DependencyProperty(name, propertyType, ownerType, metadata, validatorType, isRegistered);
lock (((ICollection)dependencyProperties).SyncRoot)
{
// 使用HashCode作为Key
if (dependencyProperties.ContainsKey(property.GetHashCode()))
{
throw new InvalidOperationException(SR.GetString("Error_DPAlreadyExist", new object[] { name, ownerType.FullName }));
}
dependencyProperties.Add(property.GetHashCode(), property);
}
return property;
}
public override int GetHashCode()
{
return (this.name.GetHashCode() ^ this.ownerType.GetHashCode());
}
}
[DesignerSerializer(typeof(DependencyObjectCodeDomSerializer), typeof(CodeDomSerializer)), DesignerSerializer(typeof(WorkflowMarkupSerializer), typeof(WorkflowMarkupSerializer))]
public abstract class DependencyObject : IComponent, IDependencyObjectAccessor, IDisposable
{
private IDictionary<DependencyProperty, object> dependencyPropertyValues;
{
// Check...
// ...
PropertyMetadata defaultMetadata = dependencyProperty.DefaultMetadata;
// 对GetValueOverride的处理
if (defaultMetadata.GetValueOverride != null)
{
return defaultMetadata.GetValueOverride(this);
}
return this.GetValueCommon(dependencyProperty, defaultMetadata);
}
{
object boundValue;
this.dependencyPropertyValues.TryGetValue(dependencyProperty, out boundValue);
// Others...
return boundValue;
}
{
// Check...
// ...
PropertyMetadata defaultMetadata = dependencyProperty.DefaultMetadata;
this.SetValueCommon(dependencyProperty, value, defaultMetadata, true);
}
{
// Check...
// ...
// 对SetValueOverride的处理
if (shouldCallSetValueOverrideIfExists && (metadata.SetValueOverride != null))
{
metadata.SetValueOverride(this, value);
}
else
{
// Others...
if (dependencyPropertyValues.ContainsKey(dependencyProperty))
{
dependencyPropertyValues[dependencyProperty] = value;
}
else
{
dependencyPropertyValues.Add(dependencyProperty, value);
}
}
}
}