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

C# 利用 Attribute 與反射實現短信模板引擎:告別硬編碼 Replace

     編輯:關於C#

短信模板關鍵字替換是常見需求。硬編碼 template.Replace("[用戶名]", name).Replace("[日期]", date)... 不僅繁瑣,擴展性差,易出錯。本文提出基於 Attribute + 反射 的通用解決方案。

核心思路

  1. 為每種模板定義實體類,屬性掛載 [Description("關鍵字")] 特性。
  2. Helper 類通過反射掃描屬性,提取 字典。
  3. 統一遍歷字典對模板執行替換。

1. 定義模板實體類

public class BirthdayMessage {
    [Description("[用戶名]")]
    public string UserName { get; set; }

    [Description("[日期]")]
    public string Date { get; set; }

    [Description("[內容]")]
    public string Content { get; set; }
}

2. 通用輔助類

public static class SmsGeneratorHelper {
    public static Dictionary<string, string> GetMessageKeyValue(object objMessage) {
        var dic = new Dictionary<string, string>();
        Type type = objMessage.GetType();
        var props = type.GetProperties();
        var descType = typeof(DescriptionAttribute);

        foreach (var prop in props) {
            // 獲取屬性值
            var value = prop.GetValue(objMessage, null);
            if (value == null) continue;

            // 獲取 Description 特性
            var attrs = prop.GetCustomAttributes(descType, true);
            if (attrs.Length == 0) continue;

            string key = ((DescriptionAttribute)attrs[0]).Description;
            dic[key] = value.ToString();
        }
        return dic;
    }
}

3. 使用示例

var msg = new BirthdayMessage {
    UserName = "張三",
    Date = DateTime.Now.ToString("yyyy-MM-dd"),
    Content = "祝你生日快樂"
};

string template = "[用戶名],今天是[日期],[內容]";
var kvDict = SmsGeneratorHelper.GetMessageKeyValue(msg);

foreach (var kvp in kvDict) {
    template = template.Replace(kvp.Key, kvp.Value);
}

Console.WriteLine(template);
// 輸出: 張三,今天是2024-01-15,祝你生日快樂

優勢

  • 零硬編碼:新增模板只需寫實體類 + 特性,無需修改替換邏輯。
  • 類型安全:編譯期檢查屬性名、類型。
  • 關注點分離:模板數據準備與替換邏輯解耦。
  • 擴展性:易於加入驗證、格式化、條件替換等邏輯到 Helper 中。

賦值實體類屬性 (如從資料庫讀取) 屬於業務層職責,不在本模式討論範圍內。

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