程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> 關於C# >> 利用Attribute和反射從模板生成短信

利用Attribute和反射從模板生成短信

編輯:關於C#

根據模板生成短信,這是一個比較常見的需求。說白了,就是如何把短信模板中的關鍵字替換掉,變成實際的、有意義的短信。

例如短信模板如下:"[用戶名],今天是[日期],[內容]",那“[用戶名]”、“[日期]”、“[內容]”,就是關鍵字。

大家會說,這還不容易,我寫個函數替換下不就行了?

public string GetMsg(string template, string userName, string date, string content)
        {
            return template.Replace("[用戶名]", userName).Replace("[日期]", date).Replace("[內容]", content);
        }

當然,這完全可以達到目的。但是如果模板很多,而且模板裡面的變量也很多的時候,到時寫替換的代碼會不會寫到手軟

呢?而且還不保證會把關鍵字替換錯呢。

所以,為了解決“替換”這個重復的而又容易出錯工作, 本文提出一種解決思路:就是利用Attribute和反射從模板生成短信。

基本思路是:針對每個短信模板編寫一個承載短信關鍵字內容的實體類,為實體類的每個屬性加上Description特性

(Attribute),通過一個Helper類獲取一個<關鍵字,值>的Dictionary,然後根據該Dictionary進行替換,得到短信。

示例實體類:

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

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

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

獲取Key-Value的Helper類代碼:

public class SmsGeneratorHelper
    {
        /// <summary>
        /// 從短信實體獲取要替換的鍵值對,用以替換短信模板中的變量
        /// </summary>
        /// <param name="objMessage">短信實體</param>
        /// <returns></returns>
        public static Dictionary<string, string> GetMessageKeyValue(object objMessage)
        {
            Type msgType = objMessage.GetType();
            Dictionary<string, string> dicMsg = new Dictionary<string, string>();
            Type typeDescription = typeof(DescriptionAttribute);
            PropertyInfo[] proList = msgType.GetProperties();

            string strKey = string.Empty;
            string strValue = string.Empty;
            foreach (PropertyInfo pro in proList)
            {
                //利用反射取得屬性的get方法。
                MethodInfo m = pro.GetGetMethod();
                //利用反射調用屬性的get方法,取得屬性的值
                object rs = m.Invoke(objMessage, null);

                object[] arr = pro.GetCustomAttributes(typeDescription, true);
                if (!(arr.Length > 0))
                {
                    continue;
                }

                DescriptionAttribute aa = (DescriptionAttribute)arr[0];
                strKey = aa.Description;

                dicMsg.Add(strKey, rs.ToString());
            }
            return dicMsg;
        }
    }

測試代碼:

 Message msg = new Message() { UserName = "張三", Content = "祝你生日快樂",Date=DateTime.Now.ToString("yyyy-MM-dd")};
        Dictionary<string,string> nvc = SmsGeneratorHelper.GetMessageKeyValue(msg);
        string template = "[用戶名],今天是[日期],[內容]";
        Console.WriteLine("模板是:{0}", template);

        foreach(KeyValuePair<string,string> kvp in nvc)
        {
            template = template.Replace(kvp.Key, kvp.Value);
        }
        Console.WriteLine("替換後的內容:{0}", template);

看到了吧,結果出來了,而那段惡心的代碼“template.Replace("[用戶名]", userName).Replace("[日期]", date).Replace("[內容]", content)”消失了。

如果有新模板了,直接寫一個模板實體類,將裡面的字段貼上[Description("xxx")]標簽就可以很方便生成短信了。

至於如何給模板實體類賦值(具體業務的問題),那就不是本文討論的范圍了。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved