你應該多想一下屬性的命名,因爲一個屬性可以同時具有getter和setter。考慮以下內容:
public class MyClass
{
private Button btnMyButton;
public Button getMyButton
{
get{ return btnMyButton; }
set{ btnMyButton = value; }
}
}
// in some other class
void ChangeActiveButton(Button newButton)
{
MyClass theThing = GetTheThing();
// This doesn't read well...
theThing.getMyButton = newButton;
}
當您實現屬性獲取器和設置器時,不要在名稱前加'get'和set'。 (對於許多開發人員來說,方法或函數中的'get'和'set'這兩個詞意味着代碼必須停止工作並完成獲取或設置,而不是簡單地返回或分配一個已經存在的值手)。
public class MyClass
{
private Button btnMyButton;
// Note that the property just has a name, no prefix.
public Button MyButton
{
get{ return btnMyButton; }
set{ btnMyButton = value; }
}
}
另外請注意,你可以讓財產的getter和setter private
即使物業本身是類暴露在外。
public Button MyButton
{
get{ return btnMyButton; }
private set{ if(null == btnMyButton) btnMyButton = value; }
}
這提供了MyClass
與priveliged訪問setter,它可以被用來實現任何特定的財產分配規則。
您也可以使用Auto-Implemented Properties,不帶額外的成員變量。
public Button MyButton { get; private set; }
c#中的屬性很棒。明智地使用它們,它將幫助您創建更好的結構化,更易於維護的代碼。
這是完全一樣的事情 –
我建議你在C性能上宣讀了#https://msdn.microsoft.com/en-us/library/w86s7x04.aspx – Jeremy
一些人認爲,前者是正確的,其他人認爲後者是正確的... –