c# - 用私有(private)属性(property)支持公共(public)属性(property)?

标签 c#

我正在查看一些代码并发现了这种模式:

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

我通常只用私有(private)字段支持我的公共(public)属性。

像这样的私有(private)属性(property)有任何理由支持属性(property)吗?我的直觉是说不应该,而应该由字段支持,对吗?我可以使用任何技术原因来支持它吗?

最佳答案

典型情况是当您有一个原始数据(未经任何转换的数据)和相同的数据,但友好表示:

  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, ...)
 } 

关于c# - 用私有(private)属性(property)支持公共(public)属性(property)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38057189/

相关文章:

c# - 在SortFieldDescriptor中使用.Suffix

c# - mvc 中创建表单的默认值

javascript - 如何从 MVC 项目中的每个表行获取每个值?

c# - AnkhSVN for Subversion 不显示源代码控制相关图标

c# - 搜索列表 C#

c# - 是否有正则表达式的通用/标准子集?

c# - 如何通过 COM Interop 在 Excel 中获取特定范围?

c# - 列表的所有排列

c# - 随着时间的推移,从 C# 调用 C++/CLI 变得越来越慢

c# - 添加服务引用给出异常 : Unable to connect to remote server