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