C#实现类似"hello $world"的格式化字符串方法
2015-11-07 15:26
489 查看
C#自带的string.Format可以格式化字符串,但是还是不太好用,由于格式的字符占位符都是数字,当数目较多时容易混淆。其实可以扩展string的方法,让C#的字符串具备其他的方法,下面介绍一个实现类似String.jQueryStringFormat("hello $world", new {world="cnblog" })的扩展方法。
View Code
也可以传入一个类的实例
1 变量前缀$
可以仿照jQuery中的选择器方法,用$作为变量前缀。例如 I love \$something 中的$someting就是变量,可以将something变量的值替换到字符串中。//模板字符串前缀 private static readonly string __prefix = "$"; // $ 正则表达式 $name private static readonly Regex VariableRegex = new Regex(@"\$(@{0,1}[a-zA-Z_\.0-9]+)");
2 正则表达式捕获变量
上面定义了变量的规则,必须是$打头的有效变量,下面将字符串用该正则表达式进行捕获private static IEnumerable<string> GetEnumerateVariables(string s) { var matchCollection = VariableRegex.Matches(s); for (int i = 0; i < matchCollection.Count; i++) { yield return matchCollection[i].Groups[1].Value; } }
3 用反射获取对象属性的值
传入的对象含有各个属性,写一个方法获取指定属性的值public static string jQueryStringFormat(this String @this, string sjQueryStringT, object oValue) { //检测验证 if (string.IsNullOrEmpty(sjQueryStringT)) return sjQueryStringT; if (!sjQueryStringT.Contains(__prefix)) throw new Exception("字符串中变量不包含$前缀"); if (oValue == null) return sjQueryStringT; //解析 //need using System.Linq; var variables = GetEnumerateVariables(sjQueryStringT).ToArray(); foreach (string vname in variables) { //获取值 string vvalue = ValueForName(oValue, vname).ToString(); //字符串替换 sjQueryStringT = sjQueryStringT.Replace("$" + vname, vvalue); } return sjQueryStringT; }
View Code
5 单元测试
其实在VS2012中可以自动生成单元测试代码,然后稍加改动就可以对编写的方法进行单元测试,非常方便/// <summary> ///jQueryStringFormat 的测试 ///</summary> [TestMethod()] public void jQueryStringFormatTest() { string @this = ""; // TODO: 初始化为适当的值 string Name = "JackWang"; int ID = 100; string sjQueryStringT = "exec func($Name,$$ID)"; // TODO: 初始化为适当的值 object oValue = new { ID, Name }; // TODO: 初始化为适当的值 string expected = "exec func(JackWang,$100)"; // TODO: 初始化为适当的值 string actual; actual = StringFormat.jQueryStringFormat(@this, sjQueryStringT, oValue); Assert.AreEqual(expected, actual); //Assert.Inconclusive("验证此测试方法的正确性。"); }
6 应用示范
string Name = "jack"; int ID = 200; string template = "exec func($Name,$ID)"; string parseText = template.jQueryStringFormat(template, new { ID, Name });
也可以传入一个类的实例
template = "the $Name who ID is $$ID"; parseText = template.jQueryStringFormat(template, new Person { ID = "2", Name = "JackWang" });
7 GitHub开源
项目源码放于GitHub中https://github.com/JackWangCUMT/jQueryStringFormat相关文章推荐
- C#各数据类型转换
- C#验证代码
- C#程序中获取各种目录
- C#中优化数据查询速度
- 【C#】获取本地硬盘分区
- c# DataTable select 过滤返回新DataTable
- C#中struct和class的区别详解
- 【C#】获取硬盘的型号,一般加密软件的手段
- 制作C#项目安装包
- c# socket udp广播
- CSharp 调用存储过程来执行增、删、改操作
- 【C#】获取系统信息
- 【C#】文件拖放到窗体
- C#操作IIS程序池及站点的创建配置实现代码
- 5.C# 串口类处理上传传感器数据
- 初探C#
- C#正则表达式匹配任意字符
- 【C#】MouseEventArgs事件参数获取鼠标的位置
- C#影院售票系统毕业设计(4)
- C#语言 类