利用反射掃描實體屬性上的 [Description] Attribute,建構 Dictionary<string, string> 供範本替換:
public static class SmsGeneratorHelper {
public static Dictionary GetMessageKeyValue(object msgEntity) {
var dict = new Dictionary();
var props = msgEntity.GetType().GetProperties();
foreach (var prop in props) {
var attrs = prop.GetCustomAttributes(typeof(DescriptionAttribute), true);
if (attrs.Length == 0) continue;
string key = ((DescriptionAttribute)attrs[0]).Description;
string value = prop.GetValue(msgEntity)?.ToString() ?? "";
dict[key] = value;
}
return dict;
}
}
var msg = new Message {
UserName = "張三",
Content = "祝你生日快樂",
Date = DateTime.Now.ToString("yyyy-MM-dd")
};
var dict = SmsGeneratorHelper.GetMessageKeyValue(msg);
string template = "[用戶名],今天是[日期],[內容]";
Console.WriteLine("範本:" + template);
foreach (var kv in dict) template = template.Replace(kv.Key, kv.Value);
Console.WriteLine("結果:" + template);
// 輸出:張三,今天是2017-01-12,祝你生日快樂
Replace 鏈,新增欄位只需在實體加 Attribute新增範本時,僅需建立對應實體類別並標註 [Description("變數名")] 即可複用此機制。