157 recommendations for writing high-quality code to improve C # programs--Recommendation 13: Format strings for type output

Source: Internet
Author: User

Recommendation 13: Format strings for type output

There are two ways to provide a formatted string output for a type. One is to realize that the type will produce a formatted string output, so the type inherits the interface IFormattable. This is a type of proactive approach that requires developers to anticipate the requirements of a type in terms of formatting. More often, the type's user needs to customize the formatter for the type, which is the second and most flexible way to provide multiple formatters for the type as the requirements change. Here's a detailed description of both approaches.

The simplest string output is to override the ToString method for a type, and if the method is not overridden for a type, the default is to call the ToString method of object, which returns the type name of the current type. But even if the ToString method is overridden, the supplied string output is very single, and by implementing the ToString method of the IFormattable interface, the type can format the output based on the user's input. As the following type of person, it itself provides properties FirstName and LastName. Now, depending on the habits of the Chinese and English language regions, the ToString method is provided to support the output "Hu Jessica" or "Jessica Hu", and the implementation code should look like this:

    classperson:iformattable { Public stringIdcode {Get;Set; }  Public stringFirstName {Get;Set; }  Public stringLastName {Get;Set; } //ways to Implement Interface IFormattable ToString         Public stringToString (stringformat, IFormatProvider formatprovider) {              Switch(format) { Case "Ch":                      return  This.                  ToString ();  Case "Eg":                      return string. Format ("{0} {1}", FirstName, LastName); default:                      return  This.              ToString (); }          }               //rewrite object.tostring ()         Public Override stringToString () {return string. Format ("{0} {1}", LastName, FirstName); }      } 

The caller code looks like this:

Person person =NewPerson () {FirstName ="Jessica", LastName ="Hu", Idcode="NB123" };      Console.WriteLine (person); Console.WriteLine (person. ToString ("Ch",NULL)); Console.WriteLine (person. ToString ("Eg",NULL));

The output is:

    Hu Jessica      hu Jessica      

The above method inherits the interface IFormattable for the type in advance when it realizes that there is a requirement for the type to be formatted for the output of the string. If the type itself does not provide the ability to format the output, this time, the formatter comes in handy. The advantage of a formatter is that it can be added or modified at any time, depending on the change in demand. Assume that the person class is implemented as shown below.

    class person      {          publicstringgetset;}            Public string Get Set ; }            Public string Get Set ; }      

The implementation of the formatter for person is:

    classPersonfomatter:iformatprovider, ICustomFormatter {#regionIFormatProvider members Public ObjectGetFormat (Type formattype) {if(Formattype = =typeof(ICustomFormatter))return  This; Else                  return NULL; }               #endregion               #regionICustomFormatter Members Public stringFormat (stringFormatObjectArg, IFormatProvider formatprovider) { person person= arg asPerson ; if(Person = =NULL)              {                  return string.              Empty; }                   Switch(format) { Case "Ch":                      return string. Format ("{0} {1}", person. LastName, person.                  FirstName);  Case "Eg":                      return string. Format ("{0} {1}", person. FirstName, person.                  LastName);  Case "ChM":                      return string. Format ("{0} {1}: {2}", person. LastName, person. FirstName, person.                  Idcode); default:                      return string. Format ("{0} {1}", person. FirstName, person.              LastName); }          }               #endregion      }

A typical formatter should inherit the interface IFormatProvider and Icustomfomatter, so the formatter should be called as follows:

Person person =NewPerson () {FirstName ="Jessica", LastName ="Hu", Idcode="NB123" }; Console.WriteLine (person.      ToString ()); Personfomatter Pformatter=NewPersonfomatter (); Console.WriteLine (Pformatter.format ("Ch", person,NULL)); Console.WriteLine (Pformatter.format ("Eg", person,NULL)); Console.WriteLine (Pformatter.format ("ChM", person,NULL));

The output is:

    Consoleapplication4.person      hu Jessica      Jessica hu      

This example also demonstrates that if the Object.ToString method is not overridden, the type will output the type name.

In fact, in the first version of the person type, if you make a slight modification to the ToString method of IFormattable, you can let the formatted output support more calls in the syntax. Note The default portion of the switch structure of the ToString method in the final version of the person type, as shown below.

    classperson:iformattable { Public stringIdcode {Get;Set; }  Public stringFirstName {Get;Set; }  Public stringLastName {Get;Set; } //ways to Implement Interface IFormattable ToString         Public stringToString (stringformat, IFormatProvider formatprovider) {              Switch(format) { Case "Ch":                      return  This.                  ToString ();  Case "Eg":                      return string. Format ("{0} {1}", FirstName, LastName); default:                      //return this.  ToString (); ICustomFormatter Customformatter =formatprovider asICustomFormatter; if(Customformatter = =NULL)                      {                          return  This.                      ToString (); }                      returnCustomformatter.format (Format, This,NULL); }          }               //rewrite object.tostring ()         Public Override stringToString () {return string. Format ("{0} {1}", LastName, FirstName); }      } 

Finally, the caller's code can support the syntax shown below:

Person person =NewPerson () {FirstName ="Jessica", LastName ="Hu", Idcode="NB123" }; Console.WriteLine (person.      ToString ()); Personfomatter Pformatter=NewPersonfomatter (); //The first class of formatted output syntaxConsole.WriteLine (Pformatter.format ("Ch", person,NULL)); Console.WriteLine (Pformatter.format ("Eg", person,NULL)); Console.WriteLine (Pformatter.format ("ChM", person,NULL)); //the second kind of formatted output syntax, more conciseConsole.WriteLine (person. ToString ("Ch", Pformatter)); Console.WriteLine (person. ToString ("Eg", Pformatter)); Console.WriteLine (person. ToString ("ChM", Pformatter));

Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia

157 recommendations for writing high-quality code to improve C # programs--Recommendation 13: Format strings for type output

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.