为什么十进制和十六进制之间的转换抛出了一个形式感觉?

Man*_*eld 0 .net c# hex decimal .net-4.5

当我编译并运行以下代码时,它会抛出以下异常:

未处理的异常:System.FormatException:指定的格式"X"在System.NumberFormatter.NumberToString(System.String format,System.Globalization.NumberFormatInfo nfi)[0x00000]中无效,其中:0处于System.NumberFormatter.NumberToString(System.String)格式,十进制值,IFormatProvider fp)[0x00000] in:0表示System.Decimal.ToString(System.String格式,IFormatProvider提供程序)[0x00000] in:0 at System.Decimal.ToString(System.String format)[0x00000] in:0在Program.Main()

using System;

class Program
{
    static void Main()
    {
        decimal result = 1454787509433225637;

                    //both these lines throw a formatexception
        Console.WriteLine(result.ToString("X"));
                    Console.WriteLine(string.Format("{0:x}", result));
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么会这样?根据/sf/answers/5195641/,这应该编译好(并输出"14307188337151A5").

Ser*_*nov 6

基于MSDN类型的XDN格式,您只能使用Integral类型.

结果:十六进制字符串. 支持者:仅限积分类型.精度说明符:结果字符串中的位数.更多信息:HexaDecimal("X")格式说明符.

所以你需要指定int而不是decimal.因为十六进制格式仅存在于整数值.