简体   繁体   中英

Backing a public property with a private property?

I'm looking at some code and found this kind of pattern:

private string text { get; set; }
public string Text
{
    get
    {
        return text;
    }
    set
    {
        text= value;
        RaisePropertyChanged("Text");
    }
}

I normally just back my public properties with private fields.

Is there any reason a property should be backed by a private property like this? My instinct is to say that it shouldn't, and this should be backed by a field instead, is that right? Any technical reasons I can use to back this up?

Typical case is when you have a raw data (data as it is without any transformation) and the same data , but friendly represented:

  private String m_RawText;

  // Text as it's obtained from, say, database 
  private string rawText { 
    get {
      if (null == m_RawText)
        m_RawText = ReadValueFromDataBase();

      return m_RawText;
    } 
    set {
      if (m_RawText != value) {
        UpdateValueInDataBase(value);

        m_RawText = value;
      }
    }  
  }

  // Friendly encoded text, for say UI
  public string Text {
    get {
      return EncondeText(rawTex);
    }
    set {
      rawText = DecodeText(value);

      RaisePropertyChanged("Text");
   }
 }  

 // Here we want rawText
 public void PerformSomething() {
   String text = rawText; // we want raw text...
   ...
 } 

 // And here we prefer Text
 public override String ToString() {
   return String.Fromat("Text = {0} ", Text, ...)
 } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM