gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:37:26 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com