短信模板關鍵字替換是常見需求。硬編碼 template.Replace("[用戶名]", name).Replace("[日期]", date)... 不僅繁瑣,擴展性差,易出錯。本文提出基於 Attribute + 反射 的通用解決方案。
[Description("關鍵字")] 特性。public class BirthdayMessage {
[Description("[用戶名]")]
public string UserName { get; set; }
[Description("[日期]")]
public string Date { get; set; }
[Description("[內容]")]
public string Content { get; set; }
}
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;
}
}
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,祝你生日快樂
賦值實體類屬性 (如從資料庫讀取) 屬於業務層職責,不在本模式討論範圍內。