每筆交易需唯一遞增 ID,程式結束時保存下一可用 ID,下次啟動恢復。標準 C++ 無內建機制,CLI 基礎庫也無,需使用 .NET 延伸 IO(File, StreamReader/Writer)實作。
ref class Transaction {
static int nextId;
int id;
static bool traceEnabled;
// 靜態建構子:型別首次使用前自動執行一次
static Transaction() {
// 從檔案讀取 nextId,檔案不存在預設 0
StreamReader^ sr = File::OpenText("txn.id");
nextId = Int32::Parse(sr->ReadLine());
sr->Close();
}
// 實例建構子
Transaction() {
id = nextId++;
}
~Transaction() { } // 解構子(非決定性)
// 靜態屬性控制 ToString 是否顯示 ID
static property bool TraceID { bool get() { return traceEnabled; } void set(bool v) { traceEnabled = v; } }
virtual String^ ToString() override {
return traceEnabled ? String::Format("[{0}]{1}", id, ...) : ...;
}
};
Transaction::TraceID = true;
Transaction^ t1 = gcnew Transaction; // [0]
Transaction^ t2 = gcnew Transaction; // [1]
// 程式結束時靜態解構子或手動儲存 nextId
static ~Transaction() 在應用程式域卸載時執行,適合寫回持久化檔案。
static Transaction() {
try {
StreamReader^ sr = File::OpenText("txn.id");
nextId = Int32::Parse(sr->ReadLine());
sr->Close();
} catch (FileNotFoundException^) { nextId = 0; }
}
static ~Transaction() {
StreamWriter^ sw = File::CreateText("txn.id");
sw->WriteLine(nextId);
sw->Close();
}
Singleton::Instance 屬性 getter 內觸發)。