简体   繁体   中英

What's the difference between the following three ToString

string ToString();
string ToString(IFormatProvider provider);
string ToString(string format, IFormatProvider provider);

With the edit:

public override string ToString()

provides the simplest formatting; it doesn't allow format specifiers and the culture is implicit. But is is convenient for showing is basic UI controls, or during debugging.

The 2 argument version allows a format and culture to be specified, and the IFormattable interface is commonly checked for by things like string.Format, and UI controls that allow the developer to specify a format to use (in particular during data-binding).

The 1-parameter version has no special significance; refer to documentation but in the example you give it seems to just allow the culture to be specified. In most cases I would actually expect a

public string ToString(string format)

to be more likely, using the current culture by default (or both to be provided).

(note: the question changed...)

You can always override ToString (unless a base-class seals it), so you can usually do something - but if you want format specifier support (ie a text-based pattern such as "###,000") IFormattable is the route - but you need to provide the implementation yourself. Note that in some cases TypeConverter may help too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM