IFormattable.ToString未按预期为十六进制格式 [英] IFormattable.ToString not working as expected for Hexadecimal formatting
问题描述
的String.Format和IFormattable.ToString(格式,值)试图格式化为十六进制时,提供了不同的结果。如何使用IFormattable.ToString(格式,值)
字符串格式=时,得到正确的结果0X {0:X4} ;
Console.WriteLine(的String.Format(格式,255)); // prints-设为0x00FF
IFormattable formattableValue =(IFormattable)255;
Console.WriteLine(formattableValue.ToString(格式,NULL)); // prints- 25X {5} X4
的格式化字符串的格式是的String.format不同()
和的ToString()
。尤其是,的String.format()
可实现环绕格式等文字,而 IFormattable.ToString()
只允许。格式说明文本本身
在您的例子中,格式字符串0X {0:X4}
被视为全格式说明的值255 0
是数字占位符,而剩下的只是多余的字符文字。
如果你想 IFormattable.ToString()
来输出相同的的String.format()
你有同等的方式来使用它:
0X+ formattableValue.ToString(X4,NULL) ;
String.Format and IFormattable.ToString(format, value) provides different result when trying to format to hexadecimal. How to get correct results when using IFormattable.ToString(format, value)
string format = "0x{0:X4}";
Console.WriteLine(string.Format(format, 255)); //prints- 0x00FF
IFormattable formattableValue = (IFormattable)255;
Console.WriteLine(formattableValue.ToString(format, null)); //prints- 25x{5:X4}
The format of the formatting string is different for string.Format()
and for ToString()
. In particular, string.Format()
allows for other text around the format, while IFormattable.ToString()
only allows the format specifier for the text itself.
In your example, the format string "0x{0:X4}"
is being treated as the whole format specifier for the value 255. The 0
are placeholders for digits, and the rest is just extra character literals.
If you want IFormattable.ToString()
to output the same as string.Format()
you have to use it in an equivalent way:
"0x" + formattableValue.ToString("X4", null);
这篇关于IFormattable.ToString未按预期为十六进制格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!