C# programming tips - setter to use Property while getter to use field

本文探讨了在面向对象编程中如何通过属性与后端字段的结合,实现数据的灵活访问与更新,同时确保依赖属性的其他字段能够同步更新,避免冗余操作并提高代码的可维护性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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. 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值