It is a common practise to have a backend field and a property that guard the access to it.
if you type something like the propful , then you will have something like this
private string backendField;
public string Property
{
get { return backendField; }
set { backendField = value; }
}
When you use the code, internally you might want to read raw data (the backend field directly), so that you will have the best flexibility.
well, you may want to call the Property when you try to set some values, because in the setter, you can also update properties/fields that depends on the property.
internal PageOrientation PageOrientation
{
get { return m_pageOrientation; }
set
{
m_pageOrientation = value;
PageOrientationString = value.ToString();
}
}
internal string PageOrientationString
{
get { return (string)GetValue(PageOrientationStringProperty); }
set {
SetAndRaisePropertyChanged(PageOrientationStringProperty, value);
}
}
// set the property via the PropertyKey and send notification on the update
// requirement on the containing object is that it should be a DependencyObject
private void SetAndRaisePropertyChanged(DependencyProperty dp, object newvalue)
{
var oldvalue = GetValue(dp);
SetValue(dp, newvalue);
OnPropertyChanged(new DependencyPropertyChangedEventArgs(dp, oldvalue, newvalue));
}
In the above code, the PageOrientationString depends on the Property of PageOrientation. so it makes sense to ripple the update when you set the value of PageOrientation; otherwise, you may call SetValue(PageOrientationProperty, value) followed by another call to SetValue(PageOrientationStringProperty, value);
which is tedious and error prone.
NOTE: another tip is that it may also fine if you read the property directly rather than read the backend field directly, it has advantage in certain situation, e..g if the property is a derived property which depends on several fields/properties.
本文探讨了在面向对象编程中如何通过属性与后端字段的结合,实现数据的灵活访问与更新,同时确保依赖属性的其他字段能够同步更新,避免冗余操作并提高代码的可维护性。
1445

被折叠的 条评论
为什么被折叠?



