IFormattable.ToString not working as expected for Hexadecimal formatting

萝らか妹 提交于 2019-12-01 20:57:00

问题


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}

回答1:


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);


来源:https://stackoverflow.com/questions/33771524/iformattable-tostring-not-working-as-expected-for-hexadecimal-formatting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!