是否可以像C printf一样在C#格式字符串中定义最大字符数? [英] Can maximum number of characters be defined in C# format strings like in C printf?

查看:83
本文介绍了是否可以像C printf一样在C#格式字符串中定义最大字符数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

找不到该怎么做。我发现的内容或多或少与此类似( http://blog.stevex .net / string-formatting-in-csharp / ):

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/):

实际上,字符串中没有任何格式,只能对齐。对齐适用于在String.Format调用中打印的任何参数。
样本生成

There really isn’t any formatting within a string, beyond it’s alignment. Alignment works for any argument being printed in a String.Format call. Sample Generates

String.Format("->{1,10}<-", "Hello");  // gives "->     Hello<-" (left padded to 10)
String.Format("->{1,-10}<-", "Hello"); // gives "->Hello     <-" (right padded to 10)


推荐答案

C#字符串格式不本地支持所需的内容,因为字符串对象的 String.ToString 方法仅返回字符串本身。

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.

调用时

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

如果someobject实现了IFormattable接口,则重载 ToString(string format,IFormatProvider formatProvider)方法被调用,其中 xxx为格式参数。

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

所以,这最多不是.NET字符串格式设计中的缺陷,而只是字符串类中缺少功能。

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.

如果确实需要此方法,则可以使用任何建议的解决方法,也可以创建自己的实现IFormattable接口的类。

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

这篇关于是否可以像C printf一样在C#格式字符串中定义最大字符数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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