C# String.Format - 它是如何工作的以及如何实现自定义格式字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10512349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
String.Format - how it works and how to implement custom formatstrings
提问by hwcverwe
With String.Format()it is possible to format for example DateTimeobjects 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()它,可以例如格式化DateTime对象在许多不同的方式。每次我寻找所需的格式时,我都需要在 Internet 上四处搜索。几乎总是我找到一个我可以使用的例子。例如:
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.Formatmap the additional informationMM/dd/yyyyto 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将附加信息映射MM/dd/yyyy到字符串结果? - 是否所有 Microsoft 对象都支持此功能?
这是在某处记录的吗? - 是否有可能做这样的事情:
String.Format("{0:MyCustomFormat}", new MyOwnClass())
采纳答案by yamen
String.Formatmatches each of the tokens inside the string ({0}etc) against the corresponding object: http://msdn.microsoft.com/en-us/library/system.string.format.aspx
String.Format将字符串({0}等)中的每个标记与相应的对象匹配:http: //msdn.microsoft.com/en-us/library/system.string.format.aspx
A format string is optionally provided:
可选地提供格式字符串:
{ index[,alignment][ : formatString] }
{ index[,alignment][ : formatString] }
If formatStringis provided, the corresponding object must implement IFormattableand specifically the ToStringmethod that accepts formatStringand returns the corresponding formatted string: http://msdn.microsoft.com/en-us/library/system.iformattable.tostring.aspx
如果formatString提供,则相应的对象必须实现IFormattable,特别ToString是接受formatString和返回相应格式化字符串的方法:http: //msdn.microsoft.com/en-us/library/system.iformattable.tostring.aspx
An IFormatProvidermay also used which can be used to capture basic formatting standards/defaults etc. Examples hereand here.
一个IFormatProvider也可以使用能够用于捕获基本格式标准/默认值等。实施例在这里和在这里。
So the answers to your questions in order:
所以按顺序回答你的问题:
It uses the
IFormattableinterface'sToString()method on theDateTimeobject and passes that theMM/dd/yyyyformat string. It is that implementation which returns the correct string.Any object that implement
IFormattablesupports this feature. You can even write your own!Yes, see above.
它在对象上使用
IFormattable接口的ToString()方法DateTime并传递MM/dd/yyyy格式字符串。正是该实现返回了正确的字符串。任何实现的对象都
IFormattable支持此功能。你甚至可以自己写!是的,见上文。
回答by Maciej
Yes, it is possible - it can be completely customized. Look at thisdocumentation link on date and time custom formatting.
是的,这是可能的 - 它可以完全定制。看这个日期和时间自定义格式文档链接。
If you have your own object it is up to you to override ToString()method and output whatever you think is appropriate representation. Once you do this you can use String.Format("{0:MyCustomFormat}", new MyOwnClass())because this implicitly calls MyOwnClass.ToString()
如果您有自己的对象,则由您来覆盖ToString()方法并输出您认为合适的表示形式。一旦你这样做,你就可以使用,String.Format("{0:MyCustomFormat}", new MyOwnClass())因为这隐式调用MyOwnClass.ToString()
回答by Dean Thomas
From my understanding, you would need to implement IFormattable in your class to support this. That then has the method, ToString which takes the parameters you pass into String.Format.
根据我的理解,您需要在类中实现 IFormattable 来支持这一点。然后有一个方法,ToString,它接受你传递给 String.Format 的参数。
Here is an example.
这是一个例子。
// Define other methods and classes here
public class Sample : IFormattable
{
public string ToString(string format, IFormatProvider provider)
{
return String.Concat("Your custom format was ", format);
}
}
String.Format("{0:MyCustomFormat}", new Sample())
回答by Fiona - myaccessible.website
The documentation for dates can be found here: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
日期文档可以在这里找到:http: //msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
That should tell you exactly what all of the date formatting characters like MM mean.
这应该会告诉您所有日期格式字符(如 MM)的确切含义。
If you want to change how a string is output for a custom class, you can override the ToString method, like this:
如果要更改自定义类的字符串输出方式,可以覆盖 ToString 方法,如下所示:
public class User
{
public string Name { get; set; }
public int Age { get; set; }
public override string ToString()
{
return this.Name + " is " + this.Age + " years old.";
}
}
and then you can just do something like myUser.ToString()and get the output you specified.
然后你可以做一些类似的事情myUser.ToString()并获得你指定的输出。
回答by Steve
Check the official MSDN docs, there is a full list of DateTime format strings here: http://msdn.microsoft.com/en-us/library/az4se3k1.aspx. There are indeed quite a few "magical" strings.
As far as I know not all types have "interesting" formatting, but all types support
ToString(). If you needed to format a built in object you could add an extension method to do it, but usuallyformatting is provided in any place where it is needed (or to put it another way, I have only written custom formatters for my own types).Yes, you can write your own and if you have data that can be formatted in different ways you probably should write a custom formatter by implementing IFormattable, again see the docs here: http://msdn.microsoft.com/en-us/library/system.iformattable.aspx. It's fairly simple, you simply check the strings provided and write out your data based on these, there's no magic behind the scenes:-)
检查官方 MSDN 文档,这里有 DateTime 格式字符串的完整列表:http: //msdn.microsoft.com/en-us/library/az4se3k1.aspx。确实有不少“神奇”的字符串。
据我所知,并非所有类型都有“有趣”的格式,但所有类型都支持
ToString(). 如果你需要格式化一个内置对象,你可以添加一个扩展方法来完成它,但通常在任何需要它的地方提供格式化(或者换句话说,我只为我自己的类型编写了自定义格式化程序) .是的,您可以编写自己的数据,如果您有可以以不同方式格式化的数据,您可能应该通过实现 IFormattable 来编写自定义格式化程序,再次参见此处的文档:http: //msdn.microsoft.com/en-us/图书馆/system.iformattable.aspx。这相当简单,您只需检查提供的字符串并根据这些字符串写出您的数据,幕后没有任何魔法:-)
回答by phipsgabler
And to answer your third question: That's not possible with this syntax, but you can provide instances of IFormatProviderand ICustomFormatterfor a type you didn't create, or implement IFormattableinside your type (although, that basically extends ToString).
并回答您的第三个问题:使用这种语法是不可能的,但是您可以为您没有创建的类型提供IFormatProvider和 的实例ICustomFormatter,或者IFormattable在您的类型中实现(尽管,这基本上是 extends ToString)。
回答by M Afifi
Under the covers String.Format does something as follows,
在幕后 String.Format 执行以下操作,
IFormattable formattable = objectToFormat as IFormattable;
if (formattable != null)
{
formattable.ToString(objectToFormat);
}
else
{
objectToFormat.ToString();
}
For your questions,
对于您的问题,
How does String.Format map the additional information MM/dd/yyyy to a string result?
As specified above, it just calls the IFormattable .ToString(string format, IFormatProvider provider). The provider is often something that tells you what the culture is of your system. Often null because people don't pass it String.Format() as you did in your case.
Does all microsoft objects support this feature? Is this documented somewhere?
Anything that implements IFormattable does.
Is it possible to do something like this:
String.Format("{0:MyCustomFormat}, new MyOwnClass())Essentially if you want your own object to do something with the format provided you implement
IFormattable.
String.Format 如何将附加信息 MM/dd/yyyy 映射到字符串结果?
如上所述,它只调用 IFormattable .ToString(string format, IFormatProvider provider)。提供者通常会告诉您系统的文化。通常为 null,因为人们不像您在案例中那样传递它 String.Format() 。
所有的微软对象都支持这个功能吗?这是在某处记录的吗?
任何实现 IFormattable 的东西都可以。
是否有可能做这样的事情:
String.Format("{0:MyCustomFormat}, new MyOwnClass())基本上,如果您希望自己的对象使用您提供的格式执行某些操作
IFormattable。
There are a huge number of supporting classes and enumerators to ensure though that format strings are largelysimilar. More here.
尽管格式字符串在很大程度上相似,但有大量支持类和枚举器可以确保。 更多在这里。

