function set 语句

声明类或接口中的新属性的访问器。 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
    必选。 要创建的属性的名称。 在类中必须是唯一的,不过同一个 propertyname 可同时与 getset 访问器一起使用,以标识可对其进行读写操作的属性。

  • parameter
    必选。 set 访问器所接受的形参。

  • type
    可选。 set 访问器的参数类型。 它必须匹配 get 访问器的返回类型(如果已定义)。

  • body
    可选。 一个或多个定义 set 访问器如何操作的语句。

备注

访问对象属性的方式与访问字段的方式基本相同,只是属性允许对存储在对象中和从对象返回的值有更多的控制。 属性可以是只读的、只写的或读写的,具体取决于在类中定义的 getset 属性访问器的组合。 属性通常用于确保 private 或 protected 字段中只存储合适的值。 不能给只读属性赋值,也不能从只写属性中读取值。

set 访问器必须恰好具有一个参数,但它不能指定返回类型。 一个 set 访问器可以与一个 get 访问器形成一对,get 访问器不具有任何参数且必须指定返回类型。 如果同时将这两个访问器用于一个属性,则 get 访问器的返回类型必须与 set 访问器的参数类型相匹配。

一个属性可以具有 get 访问器或 set 访问器,或者同时具有这两者。 只有属性的 get 访问器(如果没有 get 访问器则为 set 访问器)可以具有作为一个整体应用于此属性的自定义特性。 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 语句

概念

type 批注

其他资源

修饰符