String.Format - 它是如何工作的以及如何实现自定义格式字符串 [英] String.Format - how it works and how to implement custom formatstrings

查看:31
本文介绍了String.Format - 它是如何工作的以及如何实现自定义格式字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 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.

所以我的问题是:

  1. String.Format 如何将附加信息 MM/dd/yyyy 映射到字符串结果?
  2. 是否所有 Microsoft 对象都支持此功能?
    这是否记录在某处?
  3. 是否可以做这样的事情:
    String.Format("{0:MyCustomFormat}", new MyOwnClass())
  1. How does String.Format map the additional information MM/dd/yyyy to a string result?
  2. Do all Microsoft objects support this feature?
    Is this documented somewhere?
  3. 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:

  1. 它在 DateTime 对象上使用 IFormattable 接口的 ToString() 方法并传递 MM/dd/yyyy 格式字符串.正是该实现返回了正确的字符串.

  1. It uses the IFormattable interface's ToString() method on the DateTime object and passes that the MM/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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆