// this works fine but the output is decimal
string format = "{0:0000;-0000;''}";
Console.WriteLine(format, 10); // outputs "0010"
Console.WriteLine(format, -10); // outputs "-0010"
Console.WriteLine(format, 0); // outputs ""
但是,我要使用的格式是十六进制。我希望输出更像:
// this doesn't work
string format = "{0:'0x'X8;'0x'X8;''}";
Console.WriteLine(format, 10); // desired "0x0000000A", actual "0xX8"
Console.WriteLine(format, -10); // desired "0xFFFFFFF6", actual "0xX8"
Console.WriteLine(format, 0); // desired "", actual ""
不幸的是,当使用自定义数字格式字符串时,我不知道如何(如果可能的话)在自定义格式字符串中使用数字的十六进制表示。我的场景不允许有太多的灵活性,所以不能选择两次通过的格式。无论我做什么,都需要表示为字符串。格式样式格式字符串。
在查看了NumberFormatter的Mono源代码(该.NET实现只是遵从内部非托管代码)之后,我确认了我的怀疑。十六进制格式字符串被视为特殊情况,它只能作为标准格式字符串使用,不能用于自定义格式字符串。由于三部分格式字符串不能与标准格式字符串一起使用,所以我基本上是S.O.L。
我可能会咬紧牙关,将integer属性设置为可为null的int,并在使用zero-bleh时使用null。