Share via


function set 陳述式

更新:2007 年 11 月

宣告類別中或介面中新屬性 (Property) 的存取子。通常 function set 會與 function get 一起出現,允許讀取/寫入存取屬性。

 // Syntax for the set accessor of a property in a class.  [modifiers] function set propertyname(parameter [: type]) {    [body] }  // Syntax for the set accessor of a property in an interface. [modifiers] function set propertyname(parameter [: type])

引數

  • modifiers
    選擇項。修飾詞,控制屬性的可視性和行為。

  • propertyname
    必要項。要建立的屬性名稱。在類別中必須是唯一,除了 getset 存取子可使用相同的 propertyname 來辨識要讀取和要寫入之外的屬性。

  • parameter
    必要項。由 set 存取子接受的型式參數。

  • type
    選擇項。set 存取子的參數型別。如果已定義,則必須符合 get 存取子的傳回型別。

  • body
    選擇項。一或多個陳述式,定義 set 存取子的作業方式。

備註

物件屬性的存取方式與欄位的存取方式非常相似,除了屬性對儲存在物件中的值和由物件傳回的值允許更多的控制。屬性可以是唯讀、唯寫或讀寫,視類別內定義的 getset 屬性存取子的組合而定。屬性通常是用來確定在 private 或 protected 欄位中只會儲存適當的值。您不能指派值給唯讀屬性,或從一個唯寫屬性讀取值。

set 存取子必須剛好有一個引數,而且不能指定傳回型別。set 存取子可能與 get 存取子配對,後者沒有任何引數而且必須指定傳回型別。如果兩個存取子都用於一個屬性,get 存取子的傳回型別必須與 set 存取子的引數型別相符。

屬性可以具有 get 存取子或 set 存取子或同時擁有兩者。只有屬性 (Property) 的 get 存取子 (或 set 存取子,如果沒有 get 存取子) 可以具有套用至整體屬性 (Property) 的自訂屬性 (Attribute)。getset 存取子都具有可套用至個別存取子的修飾詞和自訂屬性。無法多載屬性存取子,但是可以隱藏或覆寫存取子。

屬性可以在 interface 的定義中指定,但是在介面中無法提供實作。

範例

下列範例說明數種屬性宣告。Age 屬性定義為讀取和寫入。唯讀 FavoriteColor 屬性也會定義。

class CPerson {
   // These variables are not accessible from outside the class.
   private var privateAge : int;
   private var privateFavoriteColor : String;

   // Set the initial favorite color with the constructor.
   function CPerson(inputFavoriteColor : String) {
      privateAge = 0;
      privateFavoriteColor = inputFavoriteColor;
   }

   // Define an accessor to get the age.
   function get Age() : int {
      return privateAge;
   }
   // Define an accessor to set the age, since ages change.
   function set Age(inputAge : int) {
      privateAge = inputAge;
   }

   // Define an accessor to get the favorite color.
   function get FavoriteColor() : String {
      return privateFavoriteColor;
   }
   // No accessor to set the favorite color, making it read only.
   // This assumes that favorite colors never change.
}

var chris : CPerson = new CPerson("red");

// Set Chris's age.
chris.Age = 27;
// Read Chris's age.
print("Chris is " + chris.Age + " years old.");

// FavoriteColor can be read from, but not written to.
print("Favorite color is " + chris.FavoriteColor + ".");

當執行此程式時,會顯示如下的輸出結果:

Chris is 27 years old.
Favorite color is red.

需求

.NET 版本

請參閱

概念

型別附註

參考

class 陳述式

interface 陳述式

function 陳述式

function get 陳述式

其他資源

修飾詞