简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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