String.Format - 它是如何工作的以及如何实现自定义格式字符串 [英] String.Format - how it works and how to implement custom formatstrings
问题描述
使用 String.Format()
可以以多种不同的方式格式化例如 DateTime
对象.每次我寻找所需的格式时,我都需要在 Internet 上四处搜索.几乎总是我找到一个我可以使用的例子.例如:
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.
所以我的问题是:
String.Format
如何将附加信息MM/dd/yyyy
映射到字符串结果?- 是否所有 Microsoft 对象都支持此功能?
这是否记录在某处? - 是否可以做这样的事情:
String.Format("{0:MyCustomFormat}", new MyOwnClass())
- 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
将字符串中的每个标记({0}
等)与对应对象:https://docs.microsoft.com/en-us/dotnet/api/system.string.format#overloads
String.Format
matches each of the tokens inside the string ({0}
etc) against the corresponding object: https://docs.microsoft.com/en-us/dotnet/api/system.string.format#overloads
可选地提供格式字符串:
A format string is optionally provided:
{ index[,alignment][ : formatString] }
如果提供了 formatString
,则相应的对象必须实现 IFormattable,特别是接受 formatString
并返回相应格式化字符串的 ToString
方法:https://docs.microsoft.com/en-us/dotnet/api/system.iformattable.tostring
If formatString
is provided, the corresponding object must implement IFormattable and specifically the ToString
method that accepts formatString
and returns the corresponding formatted string: https://docs.microsoft.com/en-us/dotnet/api/system.iformattable.tostring
IFormatProvider
也可用于捕获基本格式标准/默认值等.示例 此处 和 此处.
An IFormatProvider
may also be used to capture basic formatting standards/defaults etc. Examples here and here.
请按顺序回答您的问题:
So the answers to your questions in order:
它在
DateTime
对象上使用IFormattable
接口的ToString()
方法并传递MM/dd/yyyy
格式字符串.正是该实现返回了正确的字符串.
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.
任何实现 IFormattable
的对象都支持此功能.你甚至可以自己写!
Any object that implement IFormattable
supports this feature. You can even write your own!
是的,见上文.
这篇关于String.Format - 它是如何工作的以及如何实现自定义格式字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!