C # comes with a string. Format formats a string, but it is still not very useful, because the character placeholders in the format are numbers and are easily confused when the number is large. In fact, you can extend the string method, so that C # string has other methods, the following describes a implementation similar to String.jquerystringformat ("Hello $world", new {world= "Cnblog"}) extension method.
1 Variable prefix $
You can emulate the selector method in jquery and use $ as the variable prefix. For example I love $something $someting is a variable, you can replace the value of the something variable into a string.
1 //Template string Prefix2 Private Static ReadOnly string__prefix ="$";3 //$ regular Expression $name4 Private Static ReadOnlyRegex Variableregex =NewRegex (@"\$ (@{0,1}[a-za-z_\.0-9]+)");5
2 Regular Expression capture variables
The rule that defines the variable above must be a valid variable with a beginning, and the string is captured with the regular expression
1 Private Staticienumerable<string> Getenumeratevariables (strings)2 {3 varMatchCollection =Variableregex.matches (s);4 5 for(inti =0; i < Matchcollection.count; i++)6 {7 yield returnMatchcollection[i]. groups[1]. Value;8 }9}
3 getting the value of an object property with reflection
The incoming object contains individual attributes, and the property writes a method to get the value of the specified property
1 /// <summary>2 ///gets the corresponding property value of the object3 /// </summary>4 /// <param name= "Ovalue" >objects that contain values</param>5 /// <param name= "name" >Property name</param>6 /// <returns></returns>7 Private Static ObjectValueforname (ObjectOvalue,stringname)8 {9Type type =Ovalue.gettype ();Ten varproperty =type. GetProperty (name); One if(Property! =NULL) A { - returnProperty. GetValue (Ovalue,New Object[0]); - } the - varfield =type. GetField (name); - if(Field! =NULL) - { + returnfield. GetValue (ovalue); - } + Throw NewFormatException ("named parameter not found:"+name); A}
View Code
4 String Method Extension
1 Public Static stringJquerystringformat ( ThisString @this,stringSjquerystringt,Objectovalue)2 {3 4 //Detection Verification5 if(string. IsNullOrEmpty (sjquerystringt))6 returnSjquerystringt;7 if(!sjquerystringt.contains (__prefix))8 Throw NewException ("the variable in the string does not contain the $ prefix");9 if(Ovalue = =NULL)Ten returnSjquerystringt; One A //parsing - //need using System.Linq; - varvariables =getenumeratevariables (sjquerystringt). ToArray (); the foreach(stringVNameinchvariables) - { - //Get Value - stringVvalue =valueforname (Ovalue, VName). ToString (); + //string Substitution -Sjquerystringt = Sjquerystringt.replace ("$"+VName, vvalue); + A at } - returnSjquerystringt; -}
View Code
5 Unit Test
In fact, in the VS2012 can be automatically generated unit test code, and then a few changes can be written to the method of unit testing, very convenient
1 /// <summary>2 ///test of Jquerystringformat3 ///</summary>4 [TestMethod ()]5 Public voidjquerystringformattest ()6 {7 string@this ="";//TODO: Initialize to the appropriate value8 9 stringName ="Jackwang";Ten intID = -; One stringSjquerystringt ="exec func ($Name, $ $ID)";//TODO: Initialize to the appropriate value A ObjectOvalue =New{ID, Name};//TODO: Initialize to the appropriate value - stringexpected ="exec func (jackwang,$100)";//TODO: Initialize to the appropriate value - stringactual; theactual =Stringformat.jquerystringformat (@this, Sjquerystringt, ovalue); - assert.areequal (expected, actual); - //assert.inconclusive ("Verifies the correctness of this test method. "); -}
6 Application Demonstration
1 string " Jack " ; 2 int $ ; 3 string " exec func ($Name, $ID) " ; 4 string New {ID, Name}); 5
You can also pass in an instance of a class
1 " The $Name who ID is $ $ID " ; 2 New " 2 " " Jackwang " });
C # string.jquerystringformat ("Hello $world", new {world= "Cnblog"});