IFormattable.ToString未按预期为十六进制格式 [英] IFormattable.ToString not working as expected for Hexadecimal formatting

查看:153
本文介绍了IFormattable.ToString未按预期为十六进制格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的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屋!

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