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

根据模板生成短信,这是一个比较常见的需求。说白了,就是如何把短信模板中的关键字替换掉,变成实际的、有意义的短信。

例如短信模板如下:"[用户名],今天是[日期],[内容]",那“[用户名]”、“[日期]”、“[内容]”,就是关键字。

大家会说,这还不容易,我写个函数替换下不就行了?

Code
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进行替换,得到短信。

示例实体类:

Code
    public class Message
    {
        [Description(
"[用户名]")]
        
public string UserName { getset; }

        [Description(
"[内容]")]
        
public string Content { getset; }

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

获取Key-Value的Helper类代码:
Code
public class SmsGeneratorHelper
    {
        
/// <summary>
        
/// 从短信实体获取要替换的键值对,用以替换短信模板中的变量
        
/// </summary>
        
/// <param name="objMessage">短信实体</param>
        
/// <returns></returns>
        public static Dictionary<stringstring> GetMessageKeyValue(object objMessage)
        {
            Type msgType 
= objMessage.GetType();
            Dictionary
<stringstring> dicMsg = new Dictionary<stringstring>();
            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;
        }
    }

测试代码:
Code
 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")]标签就可以很方便生成短信了。

至于如何给模板实体类赋值(具体业务的问题),那就不是本文讨论的范围了。 

本文只提供一种思路,欢迎各位拍砖。

 


posted @ 2009-05-31 23:43  stu_acer  阅读(1928)  评论(16编辑  收藏  举报