首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

善用 Attribute 與反射從範本產生簡訊(二):通用輔助類別與測試驗證

     編輯:關於C語言

通用鍵值提取輔助類別

利用反射掃描實體屬性上的 [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("變數名")] 即可複用此機制。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved