2010-07-08 161 views
4

爲對象定義屬性而不是直接訪問私有變量有什麼好處?公共屬性定義

相反的:

public class A 

    private _x as integer = 0 

    Public property X() as integer 
     Get 
      return _x 

     End Get 
     Set(ByVal value As integer) 
      _x = value 
     End Set 
    End Property 

end class 

爲什麼我們不能做到以下幾點:

public class A 

    public _x as integer = 0 

end class 

有什麼好處?

+1

可能的重複項:http://stackoverflow.com/questions/1272521/propertywith-no-extra-processing-vs-public-field,http://stackoverflow.com/questions/1180860/c-public-fields- vs-automatic-properties,http://stackoverflow.com/questions/111461/auto-implemented-getters-and-setters-vs-public-fields,http://stackoverflow.com/questions/1277572/should-i- use-public-properties-and-private-fields-or-public-fields-for-data,http://stackoverflow.com/questions/3069901/properties-vs-fields-need-help-grasping-the-uses-屬性超越領域等等。 – 2010-07-08 13:32:19

+0

:)是啊我也發現它重複...無論如何thnx指向它 – KoolKabin 2010-07-08 18:49:27

回答

5

一個好處是,許多框架爲綁定目的而不是字段尋找類的屬性。因此,直接暴露_x字段會引起一些令人頭疼的問題,當您想知道爲什麼框架沒有按照您的預期設置值時。

另外由於封裝,您可以更改調用代碼與該字段進行交互時發生的情況。隱藏屬性getter/setter後面的字段允許您執行其他操作,如值更改時觸發,更新其他內部狀態或完全更改實現,因此它只是對子對象的包裝調用。

+0

+1這是VB6可以說比.Net更好的一點。在VB6中,直接暴露的字段的行爲與屬性完全相同。如果您需要稍後添加行爲,則可以將您的字段更改爲屬性並且不會中斷。字段和屬性之間的這種區別是爲什麼我們擁有笨重的自動實現的屬性。 – MarkJ 2010-07-08 13:08:35

1

主要原因是您可以在不更改ABI(應用程序二進制接口)的情況下向屬性添加行爲(日誌記錄,驗證,數據庫後端等)。如果你已經將它定義爲一個字段,然後想要添加行爲,則需要更改爲屬性(或方法)。其中任何一種都需要重新編譯其他代碼(並且如果您使用了方法路由,則需要進行修改)。