简体   繁体   English

以下三个ToString有什么区别

[英]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. 但是方便显示基本的UI控件或在调试过程中。

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). 2参数版本允许指定格式和区域性,并且IFormattable接口通常由诸如string.Format和允许开发人员指定要使用的格式(特别是在数据绑定期间)的UI控件检查。

The 1-parameter version has no special significance; 1参数版本没有特殊意义; 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. 您可以始终重写ToString(除非基类将其密封),因此通常可以执行某些操作 -但如果要格式说明符支持(即,基于文本的模式,例如“ ###,000”),则可以使用IFormattable -但是您需要自己提供实现。 Note that in some cases TypeConverter may help too. 请注意,在某些情况下,TypeConverter也可能会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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