. NET Foundation (iformattable) and IFormatProvider use

Source: Internet
Author: User

Use of IFormattable and IFormatProvider
1 How to use the IFormattable interface to implement formatted output
2 How to tell the type how to format the output

Use of IFormattable and IFormatProvider
1 How to use the IFormattable interface to implement formatted output

For some types, the ToString method in the overridden base class has been able to satisfy the requirements, but for some classes it is necessary to provide output in a variety of formats, when the ToString method does not meet the requirements. At this point, you need to implement the ToString method in IFormattable.

The IFormattable interface help type implements multi-style formatted output. The ToString method of IFormattable accepts a string parameter representing the format, which is formatted by parsing the parameter. In addition, the IFormattable.ToString method accepts a parameter of type IFormatProvider to allow the consumer of the type to provide a format method.

The most typical is the DateTime class, which implements the IFormattable interface.

Example:

    classuseiformattable:iformattable {PrivateDateTime _time;  Publicuseiformattable (DateTime time) {_time=Time ; }        //overriding the ToString method         Public Override stringToString () {return "object.tostring ()"; }         Publicstring ToString (string format, IFormatProvider provider) {//This section will be discussed later            if(Provider! =NULL) {ICustomFormatter FMT=provider. GetFormat ( This. GetType ()) asICustomFormatter; if(FMT! =NULL)                    returnFmt. Format (format, This, provider); }            //formatted output is implemented here            Switch(format) { Case "LD":                    return_time.                Tolongdatestring ();  Case "LT":                    return_time.                Tolongtimestring ();  Case "SD":                    return_time.                ToShortDateString ();  Case "St":                    return_time.                Toshorttimestring (); //G must implement                 Case "G":                default://nul and "" are implemented here                    return_time.            ToString (); }        }        Static voidMain (string[] args) {useiformattable use=Newuseiformattable (DateTime.Now);   Console.WriteLine (use); //the IFormattable.ToString method is calledConsole.WriteLine (use. ToString ("LD",NULL)); Console.WriteLine (use. ToString ("LT",NULL)); Console.WriteLine (use. ToString ("SD",NULL)); Console.WriteLine (use. ToString ("St",NULL));        Console.read (); }    }

Output:

2015/9/10 16:56:29
September 10, 2015
16:56:29
2015/9/10
16:56

2 How to tell the type how to format the output

IFormatProvider gives users of the type the opportunity to provide a format method. The GetFormat method returns a formatter, typically the type of the formatter that implements the ICustomFormatter type object. The IFormatProvider interface and the IFormattable interface allow for flexible and powerful format output.

Example:

    classuseiformatprovider:iformattable { PublicDateTime _time;  PublicUseiformatprovider (DateTime time) {_time=Time ; }        //overriding the ToString method         Public Override stringToString () {return "object.tostring ()"; }         Publicstring ToString (string format, IFormatProvider provider) {//This determines whether the user provides a formatter            if(Provider! =NULL) {ICustomFormatter FMT=provider. GetFormat ( This. GetType ()) asICustomFormatter; if(FMT! =NULL)                    returnFmt. Format (format, This, provider); }            //formatted output is implemented here            Switch(format) { Case "LD":                    return_time.                Tolongdatestring ();  Case "LT":                    return_time.                Tolongtimestring ();  Case "SD":                    return_time.                ToShortDateString ();  Case "St":                    return_time.                Toshorttimestring (); //G must implement                 Case "G":                default://nul and "" are implemented here                    return_time.            ToString (); }        }        Static voidMain (string[] args) {Useiformatprovider use=NewUseiformatprovider (DateTime.Now); IFormatProvider provider=NewMyProvider ();   Console.WriteLine (use); //the IFormattable.ToString method is called//the user provides a format method, and formatting the string no longer worksConsole.WriteLine (use. ToString ("LT", provider)); Console.WriteLine (use. ToString ("St", provider));        Console.read (); }    }    //implements the type of IFormatProvider,//In order to facilitate the example, the implementation of the ICustomFormatter interface, in fact, this practice is also very common    classMyprovider:icustomformatter, IFormatProvider {//implements the format method of the ICustomFormatter//The actual formatting work is done hereString Icustomformatter.format (stringFormatObjectArg, IFormatProvider formatprovider) {Useiformatprovider obj= arg asUseiformatprovider; if(obj = =NULL)                returnArg.            ToString (); returnObj._time. ToString ("YYYY-MM-DD HH:mm:ss"); }        //This type enables formatting of the Useiformatprovider type,//So first judge the type of the objectObject Iformatprovider.getformat (type type) {if(Type = =typeof(Useiformatprovider))return  This; Else                return NULL; }    }

Output:

2015/9/10 17:03:31
2015-09-10 17:03:31
2015-09-10 17:03:31

Reprint please specify the source:

Jesselzj
Source: http://jesselzj.cnblogs.com

. NET Foundation (iformattable) and IFormatProvider use

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.