2、使用變數運算式
變數運算式可用在標籤屬性,也可用在變數元素中。作用是獲取變數中某個欄位、屬性、函式方法或索引的結果值。如上例 #.var1 說明獲取 var1 變數值,即數值「1」。
對於變數值類型中真實存在的欄位、屬性或函式方法,VT 模板引擎將透過反射獲取結果值。例如:
我叫{$:user.name},今年{$:user.age}歲,我來自{$:user.location.getcity()}
假如對 user 變數賦以下類別實例值,模板引擎能正確解析各運算式最終值:
class Location { public string GetCity() { /* code */ } }
class User
{
public string Name { get; set; }
public int Age { get; set; }
public Location Location { get; set; }
}
但某些情況下,需要獲取的「值」不單純存在變數值類型中,需經過其他運算得出。如上例還要獲取用戶個人財產總額,但 User 類別裡沒有此項,導致引擎無法獲取。VT 模板引擎提供手動設定變數運算式值的方法。例如模板改為:
我叫{$:user.name},今年{$:user.age}歲,我來自{$:user.location.getcity()},我的個人財產總共有{$:user.totalmoney}元。
totalmoney 不在 User 屬性/欄位列表裡,需手動設定 {$:user.totalmoney} 值:
/// 返回某用戶個人財產總額
static int GetUserTotalMoney(User user) { /* code */ }
// 獲取 user 變數
Variable userVar = this.Document.Variables["user"];
// 產生 User 實例
User user = new User();
// ……其他程式碼略……
// 設定 user 變數值為 User 實例
userVar.Value = user;
// 手動設定 totalmoney 值(注意順序不能亂)
userVar.SetExpValue("totalmoney", GetUserTotalMoney(user));