2013-07-29 67 views
1

初學者問題:以下解決方案是否有缺點?C#:是不是使用屬性而不是公共變量來繁瑣?

public string SomeProperty { get; private set; } 

C# public variable as writeable inside the class but readonly outside the class

因爲我definetly覺得更好,比:

string someProperty; 
public string SomeProperty{ 
    get { 
     return someProperty; 
    } 
} 

但爲什麼不能C#有類似

GetOnly string someProperty; 

它會做同上?閱讀和寫作會不會更容易?

+1

要回答這個問題,沒有他們的缺點,事實上趨勢是做到這一點,而不是第二種選擇,只要微軟自動完成和像CodeRush工具去。 – Bit

+0

另外捷徑是「propg」和{hit hit tab兩次} – Bit

回答

4

自動屬性會是什麼樣的?

public Foo FooProperty { get; } 

您將如何將其值設置爲有意義的東西?

以下代碼:

public Foo FooProperty { get; private set; } 

明確指出,你可以在類的外部讀取它,並設置它只是裏面的類。

0

公共只讀字段可以工作,但只能在類構造函數中對其進行修改。

public readonly string SomeField; 

public MyClass() 
{ 
    SomeField = "SomeString"; 
} 
相關問題