Share via


expando 修飾詞

更新:2007 年 11 月

宣告類別的執行個體支援 expando 屬性,或者宣告方法是一個 expando 物件建構函式。

 expando statement

引數

  • statement
    必要項。類別或方法定義。

備註

expando 修飾詞是用來將類別標記為可動態擴充 (即支援 expando 屬性的類別)。expando 類別執行個體上的 Expando 屬性必須使用 [] 標記法來存取,它們不能使用「.」運算子存取。expando 修飾詞也可以將一個方法標記為 expando 物件建構函式。

類別和類別中的方法可以使用 expando 修飾詞來標記。欄位、屬性、介面和介面的成員不能使用 expando 修飾詞。

expando 類別具有一個隱藏、私用的屬性,稱做 Item,它會接受一個 Object 參數並且傳回一個 Object。您不能在 expando 類別上以這個簽章定義屬性。

範例 1

下列範例說明 expando 修飾詞在類別上的用法。expando 類別很像 JScript Object,但是這裡會說明一些差異。

expando class CExpandoExample {
   var x : int = 10;
}

// New expando class-based object.
var testClass : CExpandoExample = new CExpandoExample;
// New JScript Object.
var testObject : Object = new Object;

// Add expando properties to both objects.
testClass["x"] = "ten";
testObject["x"] = "twelve";

// Access the field of the class-based object.
print(testClass.x);      // Prints 10.
// Access the expando property.
print(testClass["x"]);   // Prints ten.

// Access the property of the class-based object.
print(testObject.x);     // Prints twelve.
// Access the same property using the [] operator.
print(testObject["x"]);  // Prints twelve.

這個程式碼的輸出為:

10
ten
twelve
twelve

範例 2

下列範例說明 expando 修飾詞在方法上的用法。以一般方式呼叫 expando 方法時,它會存取 x 欄位。當該方法搭配 new 運算子做為一個明確的建構函式使用時,它會將 expando 屬性加入新物件之中。

class CExpandoExample {
   var x : int;
   expando function constructor(val : int) {
      this.x = val;
      return "Method called as a function.";
   }
}

var test : CExpandoExample = new CExpandoExample;
// Call the expando method as a function.
var str = test.constructor(123);
print(str);        // The return value is a string.
print(test.x);     // The value of x has changed to 123.

// Call the expando method as a constructor.
var obj = new test.constructor(456);
// The return value is an object, not a string.
print(obj.x);      // The x property of the new object is 456.
print(test.x);     // The x property of the original object is still 123.

這個程式碼的輸出為:

Method called as a function.
123
456
123

需求

.NET 版本

請參閱

概念

變數和常數範圍

型別附註

參考

static 修飾詞

var 陳述式

function 陳述式

class 陳述式

其他資源

修飾詞