.exe,否則 .dll。取代傳統 obj+link 模式。| 分類 | 關鍵字 | 特性 | 範例 |
|---|---|---|---|
| 參考型別 | ref class/struct | GC 堆分配、參考語意、支援繼承、虛函數、介面 | String, 自訂類別 |
| 實值型別 | value class/struct | 堆疊/內嵌分配、複製語意、無繼承、輕量 | int, DateTime, Point |
| 介面 | interface class/struct | 純合約、多重實作、無欄位、無建構子 | IEnumerable, ICloneable |
| 委派 | delegate | 函數包裝、多播、型別安全 | EventHandler, Comparison |
| 列舉 | enum class | 強型別、具底層型別、作用域限定 | TransactionType |
using namespace System;
public ref class Point {
int x, y;
public:
property int X { int get() { return x; } void set(int v) { x = v; } }
property int Y { int get() { return y; } void set(int v) { y = v; } }
Point() : X(0), Y(0) {}
Point(int xor, int yor) : X(xor), Y(yor) {}
void Move(int xor, int yor) { X = xor; Y = yor; }
virtual bool Equals(Object^ obj) override {
if (obj == nullptr) return false;
if (this == obj) return true;
if (GetType() != obj->GetType()) return false;
Point^ p = safe_cast(obj);
return X == p->X && Y == p->Y;
}
virtual int GetHashCode() override { return X ^ (Y << 1); }
virtual String^ ToString() override { return String::Format("({0},{1})", X, Y); }
};
property:編譯器自動產生 get_X/set_X 方法,支援唯讀/唯寫/存取層級差異。virtual ... override:明確覆寫基類虛擬方法,編譯器檢查簽章一致。safe_cast:執行期型別檢查轉型,失敗拋 InvalidCastException(優於 static_cast)。gcnew:配置於 GC 堆,回傳控制碼 ^。所有 BCL 型別位於 System 或巢狀命名空間。using namespace System; 可省略前綴。