典型的情況是,當你有一個原始數據(數據,因爲它是沒有任何變換)和相同的數據,但友好的表示:
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, ...)
}
沒有理由這是行不通的。你遇到過這個問題嗎? – David
這裏沒有任何技術限制,儘管我認爲最好的做法總是規定在這種情況下使用字段。 –
嗯,我沒有看到這樣做的好理由,但從技術上說沒有理由不應該這樣做。可能會涉及更多的開銷,但是如果你這樣做(必須比較IL輸出),這就是爲什麼我會使用變量而不是其他屬性的經典方式。無論如何,也可以是優化器將私有屬性轉換爲字段? –