共用方式為


__property

注意事項注意事項

本主題僅適用於第 1 版的 Managed Extensions for C++。這個語法只應該用於維護第 1 版的程式碼。請參閱屬性如有關在新語法中使用的相等功能。

宣告是 managed 類別的純量] 或 [索引] 屬性。

__property function-declarator

備註

__property關鍵字引入屬性的宣告,而且可以出現在類別、 介面和實值型別。 屬性可以具有的 getter 函式 (唯讀),set 存取子函數 (唯) 或這兩個 (讀 / 寫)。

注意事項注意事項

屬性名稱不能與包含它的 managed 類別的名稱相符。Getter 函式的傳回型別必須符合相對應的 set 存取子函式的最後一個參數的型別。

範例

在下列範例中,純量屬性 (Size) 加入至MyClass宣告。 屬性是然後隱含設定,並使用擷取get_Size和set_Size函式:

// keyword__property.cpp
// compile with: /clr:oldSyntax
#using <mscorlib.dll>
using namespace System;

__gc class MyClass {
public:
   MyClass() : m_size(0) {}
   __property int get_Size() { return m_size; }
   __property void set_Size(int value) { m_size = value; }
   // compiler generates pseudo data member called Size
protected:
   int m_size;
};

int main() {
   MyClass* class1 = new MyClass;
   int curValue;

   Console::WriteLine(class1->Size);
   
   class1->Size = 4;   // calls the set_Size function with value==4
   Console::WriteLine(class1->Size);

   curValue = class1->Size;   // calls the get_Size function
   Console::WriteLine(curValue);
}

Output

0
4
4