惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Recent Announcements
Recent Announcements
V
Visual Studio Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
云风的 BLOG
云风的 BLOG
Microsoft Security Blog
Microsoft Security Blog
博客园 - 司徒正美
Y
Y Combinator Blog
Stack Overflow Blog
Stack Overflow Blog
雷峰网
雷峰网
小众软件
小众软件
GbyAI
GbyAI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
aimingoo的专栏
aimingoo的专栏
MyScale Blog
MyScale Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
腾讯CDC
A
About on SuperTechFans
宝玉的分享
宝玉的分享
WordPress大学
WordPress大学
B
Blog RSS Feed
G
Google Developers Blog
量子位
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 三生石上(FineUI控件)

博客园 - stu_acer

对C#对象的Shallow、Deep Cloning认识【转】 PowerShell 启动应用程序【转】 把boolean 参数放到最后面(Put boolean arguments last)【转载】 几个收藏的根据数据库生成Insert语句的存储过程[修正版] SQL Server删除外键约束 IE6下PNG图片透明显示解决方法(From QQ) 用Regex类计算一个字符串出现次数是最好方法【转载】 C#有关Session 操作的几个误区【转】 - stu_acer - 博客园 DataList绑定数据到泛型类(Dictionary) 【转】 重写Asp.NET2.0 TreeView的折叠/展开方法(TreeView_ToggleNode) javascript window.close() 去掉那讨厌的确认对话框【转】 thickbox使用技巧【转】 - stu_acer - 博客园 jQuery操作checkbox的例子(全选,反选,获取选取值)【转】 查看SQL Server 2005版本号 创建SQL索引,查看SQL性能语句收集 ddlevelsmenu在IE6下,与select冲突的解决办法【整理】 IE6 Select元素无法被div等元素覆盖的bug解决办法【zz】 Session & Cookie 的使用建议(zz) - stu_acer AdventureWorks、Northwind、pubs示例数据库下载
利用Attribute和反射从模板生成短信 - stu_acer - 博客园
stu_acer · 2009-05-31 · via 博客园 - stu_acer

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

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

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

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

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

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