您的位置:首页 > 编程语言 > C#

C#实现类似"hello $world"的格式化字符串方法

2015-11-07 15:26 489 查看
  C#自带的string.Format可以格式化字符串,但是还是不太好用,由于格式的字符占位符都是数字,当数目较多时容易混淆。其实可以扩展string的方法,让C#的字符串具备其他的方法,下面介绍一个实现类似String.jQueryStringFormat("hello $world", new {world="cnblog" })的扩展方法。

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: