Can maximum number of characters be defined in C# format strings like in C printf?

后端 未结 6 632
失恋的感觉
失恋的感觉 2020-12-10 01:42

Didn\'t find how to do that. What I found was more or less on the lines of this (http://blog.stevex.net/string-formatting-in-csharp/):

There really isn’t any formatt

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-10 02:03

    What you want is not "natively" supported by C# string formatting, as the String.ToString methods of the string object just return the string itself.

    When you call

    string.Format("{0:xxx}",someobject);
    

    if someobject implements the IFormattable interface, the overload ToString(string format,IFormatProvider formatProvider) method gets called, with "xxx" as format parameter.

    So, at most, this is not a flaw in the design of .NET string formatting, but just a lack of functionality in the string class.

    If you really need this, you can use any of the suggested workarounds, or create your own class implementing IFormattable interface.

提交回复
热议问题