的String.Format - 它是如何工作以及如何实现自定义formatstrings [英] String.Format - how it works and how to implement custom formatstrings
问题描述
使用的String.Format()
有可能在许多不同的方式,例如格式化的DateTime
的对象。每次我要寻找一个所需的格式,我需要四处搜寻互联网上。几乎每次我找到一个例子,我可以使用。例如:
的String.Format({0:MM / DD / YYYY},DateTime.Now); //09/05/2012
不过,我没有任何线索,它是如何工作的,并哪些类支持这些神奇的附加字符串。
所以我的问题是:
- 如何
的String.Format
映射的附加信息MM / DD / YYYY
来字符串结果? - 请所有微软对象支持此功能结果
这是什么地方记录 - 是否有可能做这样的事情:??结果
的String.Format({0:MyCustomFormat},新的个MyOwnClass())
的String.Format
匹配每个字符串(里面的标记{0}
等)对相应的对象: http://msdn.microsoft.com/en-us/库/ system.string.format.aspx
一个格式字符串根据需要而设置:
{索引[,对齐] [:formatString中]}
如果的formatString
提供,相应的对象必须实现 IFormattable 并专门的ToString
接受的方法的formatString
并返回相应的格式化字符串:的http://msdn.microsoft.com/en-us/library/system.iformattable.tostring.aspx
这是的IFormatProvider
也可使用,可用于捕获基本的格式标准/默认值等例子的这里和的这里
所以,问题的答案依次是:
-
它使用
IFormattable
接口的的ToString()
的的DateTime
对象的方法,并通过了MM / DD / YYYY
格式字符串。这是返回正确的字符串执行。 -
这是实现任何物体
IFormattable
支持此功能。你甚至可以编写自己的! -
是的,见上面。
With String.Format()
it is possible to format for example DateTime
objects in many different ways. Every time I am looking for a desired format I need to search around on Internet. Almost always I find an example I can use. For example:
String.Format("{0:MM/dd/yyyy}", DateTime.Now); // "09/05/2012"
But I don't have any clue how it works and which classes support these 'magic' additional strings.
So my questions are:
- How does
String.Format
map the additional informationMM/dd/yyyy
to a string result? - Do all Microsoft objects support this feature?
Is this documented somewhere? - Is it possible to do something like this:
String.Format("{0:MyCustomFormat}", new MyOwnClass())
String.Format
matches each of the tokens inside the string ({0}
etc) against the corresponding object: http://msdn.microsoft.com/en-us/library/system.string.format.aspx
A format string is optionally provided:
{ index[,alignment][ : formatString] }
If formatString
is provided, the corresponding object must implement IFormattable and specifically the ToString
method that accepts formatString
and returns the corresponding formatted string: http://msdn.microsoft.com/en-us/library/system.iformattable.tostring.aspx
An IFormatProvider
may also used which can be used to capture basic formatting standards/defaults etc. Examples here and here.
So the answers to your questions in order:
It uses the
IFormattable
interface'sToString()
method on theDateTime
object and passes that theMM/dd/yyyy
format string. It is that implementation which returns the correct string.Any object that implement
IFormattable
supports this feature. You can even write your own!Yes, see above.
这篇关于的String.Format - 它是如何工作以及如何实现自定义formatstrings的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!