The tostring () method that you do not know

Source: Internet
Author: User
1.1.1 Summary

I believe you are not familiar with the tostring () method, because the method is. netProgramIn addition to calling the tostring () method, some methods in. Net also implicitly call the tostring () method (WPF, Windows form, and Silverlight ).

1.1.2 text

First, let's take a look at the origin of tostring (). It is a virtual method provided by the object class. The tostring () method returns a string to display the type of the object that calls this method, the object class is implemented as follows.

 
//// Tostring () Implementation in objectPublic Virtual stringTostring (){Return this. GetType (). tostring ();}

Now we know that the object class provides a virtual tostring () method, indicating that. net also provides the override tostring () method, which allows us to define a customer class and then use the console. the writeline () method implicitly calls the tostring () method output of the customer class. Note that the tostring method has not been rewritten, so we call the tostring () method of the object class.

 /// <Summary> /// Customer has three Properities  ///  Name, revenum and Tel.  /// </Summary>  Public class  Customer   { Private string _ Name; Private decimal _ Revenue; Private string _ Tel; Private string _ Zip; /// <Summary> ///  Initializes a new instance of <See CREF = "customer"/>  Class.  /// </Summary>  Public Customer ( String Name, Decimal Revenue, String Tel, String Zip ){ This . Name = Name; This . Revenue = revenue; This . Tel = Tel; This . Zip = zip ;}/// <Summary> ///  Gets or sets the name.  /// </Summary> /// <value> ///  The name.  /// </Value>  Public String Name { Get { Return _ Name ;} Set {_ Name = Value ;}} /// <Summary> ///  Gets or sets the revenue. /// </Summary> /// <value> ///  The revenue.  /// </Value>  Public decimal Revenue { Get { Return _ Revenue ;} Set {_ Revenue = Value ;}} /// <Summary> ///  Gets or sets the Tel.  /// </Summary> /// <value> ///  The Tel. /// </Value>  Public String Tel { Get { Return _ Tel ;} Set {_ Tel = Value ;}} /// <Summary> ///  Gets or sets the zip.  /// </Summary> /// <value> ///  The zip.  /// </Value>  Public String Zip { Get {Return _ Zip ;} Set {_ Zip = Value ;}}}
 
 

Figure 1 output type string

Retostring () method

We can clearly explain that when the tostring () method is not re-called, we call the tostring () method of the parent class object. Not only does its output not make sence, but it does not output the value we need, so let's rewrite the tostring () method.

 

 
Public override stringTostring (){//// Implemention code.}

 

We overwrite the tostring () method to return the name, revenuehe, and Tel attributes. Then we use the writeline () method to call the tostring () method implicitly (. NET provides explicit and implicit calls to tostring () methods, such as console. writeline, String. format and.. Net Control ).

Although the simple tostring () method can meet our needs many times, sometimes we still need a more powerful method to format the output string. (For example, phone number, date and zip code)

To implement the above format, we can solve this problem by implementing the iformattable interface. The iformattable Interface contains an overloaded tostring () method, which allows us to specify certain format information for the type. This interface is useful when we need to create different forms of string output for the type.

  1. Implement the iformattable Interface

    Now let's modify our customer class to implement the iformattable interface, and then rewrite the tostring () method to implement the following:

     

     /// <Summary> ///  Customer has three Properities  ///  Name, revenum and Tel. /// </Summary>  Public class  Customer : Iformattable { Private string _ Name; Private decimal _ Revenue; Private string _ Tel; Private string _ Zip; /// <Summary> ///  Initializes a new instance of  <See CREF = "customer"/>  Class.  /// </Summary> Public Customer ( String Name, Decimal Revenue, String Tel, String Zip ){ This . Name = Name; This . Revenue = revenue; This . Tel = Tel; This . Zip = zip ;} /// <Summary> ///  Gets or sets the name.  /// </Summary> /// <value> /// The name.  /// </Value>  Public String Name { Get { Return _ Name ;} Set {_ Name = Value ;}} /// <Summary> ///  Gets or sets the revenue.  /// </Summary> /// <value> ///  The revenue.  /// </Value>  Public decimal Revenue { Get { Return _ Revenue ;} Set {_ Revenue = Value ;}} /// <Summary> ///  Gets or sets the Tel.  /// </Summary> /// <value> ///  The Tel.  /// </Value>  Public String Tel { Get { Return _ Tel ;}Set {_ Tel = Value ;}} /// <Summary> ///  Gets or sets the zip.  /// </Summary> /// <value> ///  The zip.  /// </Value>  Public String Zip { Get { Return _ Zip ;} Set {_ Zip = Value ;}} # Region Iformattable Member /// <Summary> ///  Override tostring method,  ///  And custom output string format.  /// </Summary> /// <Param name = "format"> </param> /// <Param name = "formatprovider"> </param> /// <returns> </returns>  Public String Tostring ( String Format, Iformatprovider Formatprovider ){ If (Formatprovider! = Null ){Icustomformatter FMt = formatprovider. getformat ( This . GetType ()) As  Icustomformatter ; If (FMT! = Null ){ Return FMT. Format (format, This , Formatprovider );}} Switch (Format ){ Case  "LC" : Return string . Format ( "Name: {0} \ nrevenue: {1: C2} \ ntel: {2} \ NZIP: {3} \ n" , Name. tolower (), revenue, Tel. Replace ( "_" , "-" ), Zip. Replace ( "_" , "" )); Case  "UC" : Return string . Format ( "Name: {0} \ nrevenue: {1: C3} \ ntel: {2} \ NZIP: {3} \ n" , Name. toupper (), revenue, Tel. Replace ( "_" ,":" ), Zip. Replace ( "_" , "" )); Case  "G" : Return string . Format ( "Name: {0} \ nrevenue: {1} \ ntel: {2} \ NZIP: {3} \ n" , Name, revenue, tel, zip ); Default : Return  "" ;}} # Endregion }

     Class Program { /// <Summary> ///  The client calls the tostring () method.  /// </Summary> /// <Param name = "ARGs"> </param>  Static void Main ( String [] ARGs ){ Customer Objcustomer = New  Customer ( "Jk_rush" , 8888, "0723_98765423" , "65_4321" ); Console . Writeline (objcustomer. tostring ( "LC" , Null )); Console . Readkey ();}  }

Figure 2 Implementation of iformattable

Make our design conform to OCP

Now our customer class implements the iformattable interface, then overrides the tostring () method, and then provides three formatting types of output. OK. Now our output string has a better custom format, however, the format required by users is constantly changing. We cannot estimate and predict the output format of user requirements. Do we need to add the format in the switch whenever it does not meet user requirements? We can do this. This seems straightforward, but it does not conform to the OCP principles of the design model. Fortunately. NET provides implementation methods that comply with the OCP principles. By implementing the iformattable interface, the class implementing this interface is modified and disabled for stringfomat (). When the class implementing the icustomformatter interface is open to stringfomat () extension.

"Software entities (classes, modules, functions, etc.) shocould be open for extension,

But closed for modification [Martin, p.99]"

Now we add the custom class customformatprovider, which can be used to extend the format type of the output string of the customer, and avoid complying with the OCP for the modification of the customer class, and then implement the interface iformatprovider and icustomformatter, implement the string output format in the format () method.

 /// <Summary> ///  Custom string format provider.  /// </Summary>  Public class  Customformatprovider : Iformatprovider , Icustomformatter { // Methods  # Region Iformatprovider? Member? /// <Summary> ///  Get format provider object.  /// </Summary> /// <Param name = "formattype"> </param> /// <returns>  The customformatprovider object.  </Returns>  Public object Getformat ( Type Formattype ){ If (Formattype = Typeof ( Icustomformatter )){ Return new Customformatprovider ();} Return null ;} # Endregion # Region Icustomformatter? Member? Public String Format ( String Format, Object Arg, Iformatprovider Formatprovider ){ Customer C = ARG As  Customer ; If (C! = Null ){/// Custom string output format.  Switch (Format ){ Case  "Custom" : Return string . Format ( "Name: {0} \ nrevenue: {1: C4} \ ntel: {2} \ NZIP: {3} \ n" , C. Name. toupper (), C. Revenue, C. Tel. Replace ( "_" , ":" ), C. Zip. Replace ( "_" , "-" )); Default : Return  "" ;}} Return  "" ;} # Endregion }
  class   Program  {///  ///   the client calls the tostring () method   ///  ///     static void  main ( string  [] ARGs) { customer  objcustomer =  New   customer  (" jk_rush ", 8888, " 0723_98765423 ", " 65_4321 "); 
Console. Writeline (String. Format (NewCustomformatprovider(),"{0: Custom }", Objcustomer ));
 
Console. Readkey ();}}

Figure 4 custom string format

 

 
 

Figure 5 custom format implementation framework

The preceding getformat () method creates an object that implements the icustomformatter interface, and uses the format () method to customize the output string format. It passes different format parameters to specify different format options.

1.1.3 Summary

Whether or not a class implements the iformattable interface, we can create an implementation class for iformatprovider and icustomformatter. Therefore, even if a class does not provide reasonable tostring () behavior, we can still provide formatting support for it. Of course, as an external visitor of a class, we can only construct strings by accessing the public attributes and data members. Although writing format provider classes (implementing iformatprovider and icustomformatter respectively) requires a lot of work, and its purpose is only to get a string. However, once we use this method to implement our own defined string output, they will be supported everywhere in the. NET Framework.

Now let's go back to the class role. Rewriting object. tostring () is the simplest way to provide string representation for the class. This method is required every time we create a type. It should be the most obvious and commonly used expression of our type. In addition, the iformattable interface should be implemented only when we want to provide more complex output formats for types. It provides a standard method for "custom string output for type users. If we do not do this, you need to customize the formatter yourself. Such practices require moreCodeBecause the user is out of class and cannot access the internal state of the object.

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.