Type custom Format String

Source: Internet
Author: User

Introduction

String may be the most commonly used type, and ToString () should be the most commonly used method. However, it should not only be used to output the type name. if used properly, it can easily output our custom format for the type. This article will gradually discuss ToString () and related IFormattable, IFormatProvider, and ICustomFormatter interfaces.

The custom format string is provided within the type to inherit from the ToString () of the System. Object base class ()

String is one of the data types that people can understand directly. In many cases, we expect to get a String output of the type. Therefore, Microsoft provides a virtual ToString () method in the base class System. Object of all types of. Net Framework. Its default implementation is the type name of the returned Object.

Suppose we have such a type, which defines some information about the object "friend:

Namespace CustomToString
Public class Friend {
Private string familyName; // surname
Private string firstName; // name

Public Friend (string familyName, string firstName ){
This. familyName = familyName;
This. firstName = firstName;
}
Public Friend (): this ("Zhang", "Zi Yang "){}

Public string FamilyName {
Get {return familyName ;}
}

Public string FirstName {
Get {return firstName ;}
}
}
}

When the ToString () method is called on the Friend instance, the type name CustomToString. Friend is returned.

Friend f = new Friend ();
Console. WriteLine (f. ToString (); // output: CustomToString. Friend

Overwrite the ToString () method

In the above example, regardless of the data (Field Value) contained in the type instance (object), it always returns the same result (CustomToString. Friend ). In many cases, returning the type name of an object does not make much sense for us. In the above example, we may expect to be able to return the name of a friend (value of the famliyName and firstName fields ). At this time, we can simply overwrite the ToString () method of the System. Object base class, and add the following method to the Friend class:

// Overwrite the ToString () method of the System. Object base class
Public override string ToString (){
Return String. Format ("Friend: {0} {1}", familyName, firstName );
}

Run the code again:

Friend f = new Friend ();
Console. WriteLine (f. ToString (); // output: Friend: Zhang Ziyang
F = new Friend ("Wang", "Tao ");
Console. WriteLine (f. ToString (); // output: Friend: Wang Tao

We can see that for different objects, ToString () returns different results based on the object's field value, which makes more sense to us.

Overload ToString () method

Sometimes, we may need to format the object in different ways. Taking the Friend type as an example: Westerners are the first and last names, while Chinese are the first and last names. So if you run the following code, although the program will not go wrong, there is a problem from the perspective of English syntax:

Friend a = new Friend ("Zhang", "Jimmy ");
Console. WriteLine (a. ToString (); // output: Friend: ZhangJimmy

What we expect is Jimmy Zhang. At this time, you can think about how to solve this problem using. Net Framework: Reload ToString (). Let the ToString () method receive a parameter and format it accordingly. For example, int a = 123; Console. WriteLine (a. ToString ("c"); specifies the string "c" as the parameter to generate the output of the currency type: ¥123.00. We can also use this method to improve the Friend class, And reload a ToString () method in the Friend to define its string formatting based on a character parameter:

// Define the type formatting Based on string Parameters
Public string ToString (string format ){
Switch (format. ToUpper ()){
Case "W": // West: Western
Return String. Format ("Friend: {0} {1}", firstName, familyName );
Case "E": // East: East
Return this. ToString ();
Case "G": // General
Default:
Return base. ToString ();
}
}

Then we can use the overloaded version when using the ToString () method. For English names, we pass in "W" as the parameter, which solves the above problem:

Friend f = new Friend ();
Console. WriteLine (f. ToString (); // output: Friend: Zhang Ziyang

F = new Friend ("Zhang", "Jimmy ");
Console. WriteLine (f. ToString ("W"); // output: Friend: Jimmy Zhang

NOTE:A better solution to this problem is not to overload ToString (), which can be simply done using attributes, such:

Public string comment fullna

Related Article

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.