简体   繁体   English

IFormattable.ToString 对于十六进制格式没有按预期工作

[英]IFormattable.ToString not working as expected for Hexadecimal formatting

String.Format and IFormattable.ToString(format, value) provides different result when trying to format to hexadecimal. String.Format 和 IFormattable.ToString(format, value) 在尝试格式化为十六进制时提供不同的结果。 How to get correct results when using IFormattable.ToString(format, value)使用 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() . string.Format()ToString()的格式化字符串的格式不同。 In particular, string.Format() allows for other text around the format, while IFormattable.ToString() only allows the format specifier for the text itself.特别是, string.Format()允许格式周围的其他文本,而IFormattable.ToString()只允许文本本身的格式说明符。

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.在您的示例中,格式字符串"0x{0:X4}"被视为值 255 的整个格式说明符0是数字的占位符,其余的只是额外的字符文字。

If you want IFormattable.ToString() to output the same as string.Format() you have to use it in an equivalent way:如果您希望IFormattable.ToString()输出与string.Format()相同的输出,则必须以等效的方式使用它:

"0x" + formattableValue.ToString("X4", null);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM