zoukankan      html  css  js  c++  java
  • C#实现类似"hello $world"的格式化字符串方法

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

    1 变量前缀$

    可以仿照jQuery中的选择器方法,用$作为变量前缀。例如 I love $something 中的$someting就是变量,可以将something变量的值替换到字符串中。

    1 //模板字符串前缀
    2 private static readonly string __prefix = "$";
    3 // $ 正则表达式 $name
    4 private static readonly Regex VariableRegex = new Regex(@"$(@{0,1}[a-zA-Z_.0-9]+)");
    5         

    2 正则表达式捕获变量

    上面定义了变量的规则,必须是$打头的有效变量,下面将字符串用该正则表达式进行捕获

    1 private static IEnumerable<string> GetEnumerateVariables(string s)
    2 {
    3      var matchCollection = VariableRegex.Matches(s);
    4 
    5      for (int i = 0; i < matchCollection.Count; i++)
    6      {
    7         yield return matchCollection[i].Groups[1].Value;
    8      }
    9 }

    3 用反射获取对象属性的值

    传入的对象含有各个属性,写一个方法获取指定属性的值

     1         /// <summary>
     2         /// 获取对象的对应属性值
     3         /// </summary>
     4         /// <param name="oValue">包含值的对象</param>
     5         /// <param name="name">属性名</param>
     6         /// <returns></returns>
     7         private static object ValueForName(object oValue, string name)
     8         {
     9             Type type = oValue.GetType();
    10             var property = type.GetProperty(name);
    11             if (property != null)
    12             {
    13                 return property.GetValue(oValue, new object[0]);
    14             }
    15 
    16             var field = type.GetField(name);
    17             if (field != null)
    18             {
    19                 return field.GetValue(oValue);
    20             }
    21             throw new FormatException("未找到命名参数: " + name);
    22         }
    View Code

    4 String方法扩展

     1         public static string jQueryStringFormat(this String @this, string sjQueryStringT, object oValue)
     2         {
     3        
     4             //检测验证
     5             if (string.IsNullOrEmpty(sjQueryStringT))
     6                 return sjQueryStringT;
     7             if (!sjQueryStringT.Contains(__prefix))
     8                 throw new Exception("字符串中变量不包含$前缀");
     9             if (oValue == null)
    10                 return sjQueryStringT;
    11 
    12             //解析
    13             //need  using System.Linq;
    14             var variables = GetEnumerateVariables(sjQueryStringT).ToArray();
    15             foreach (string vname in variables)
    16             {
    17                 //获取值
    18                 string vvalue = ValueForName(oValue, vname).ToString();
    19                 //字符串替换
    20                 sjQueryStringT = sjQueryStringT.Replace("$" + vname, vvalue);
    21                
    22 
    23             }
    24             return sjQueryStringT;
    25         }
    View Code

    5 单元测试

    其实在VS2012中可以自动生成单元测试代码,然后稍加改动就可以对编写的方法进行单元测试,非常方便

     1        /// <summary>
     2         ///jQueryStringFormat 的测试
     3         ///</summary>
     4         [TestMethod()]
     5         public void jQueryStringFormatTest()
     6         {
     7             string @this = ""; // TODO: 初始化为适当的值
     8 
     9             string Name = "JackWang";
    10             int ID = 100;
    11             string sjQueryStringT = "exec func($Name,$$ID)"; // TODO: 初始化为适当的值
    12             object oValue = new { ID, Name }; // TODO: 初始化为适当的值
    13             string expected = "exec func(JackWang,$100)"; // TODO: 初始化为适当的值
    14             string actual;
    15             actual = StringFormat.jQueryStringFormat(@this, sjQueryStringT, oValue);
    16             Assert.AreEqual(expected, actual);
    17             //Assert.Inconclusive("验证此测试方法的正确性。");
    18         }

    6 应用示范

    1 string Name = "jack";
    2 int ID = 200;
    3 string template = "exec func($Name,$ID)";
    4 string parseText = template.jQueryStringFormat(template, new { ID, Name });
    5            

    也可以传入一个类的实例

    1 template = "the $Name who ID is $$ID";
    2 parseText = template.jQueryStringFormat(template, new Person { ID = "2", Name = "JackWang" });

     7 GitHub开源

    项目源码放于GitHub中https://github.com/JackWangCUMT/jQueryStringFormat

  • 相关阅读:
    微信小程序demo理解
    HTML 和 JavaScript 编写简单的 404 界面
    阿里云实现简单的运行 Django 项目
    AJAX 与 Python 后台通信
    django session 使用案例
    PHP 基础知识
    Django 搭建后台 favicon.ico 文件操作
    Win10 Ubuntu 双系统 卸载 Ubuntu
    JavaScript 表单验证 案例
    JavaScript Image对象 / Tabel对象 / Select对象 / Form对象
  • 原文地址:https://www.cnblogs.com/isaboy/p/jquery_string_format.html
Copyright © 2011-2022 走看看