【发布时间】:2018-05-23 14:52:08
【问题描述】:
我有一个自定义格式化程序,如果 arg 为 null,则返回 null。但是,string.Format(MyCustomFormatProvider, {0:some-custom}, null) 返回一个空字符串。有没有办法解决这个问题?
我了解string.Format 状态的文档:
如果参数的值为空,格式项替换为 字符串.空。
我希望ICustomFormatter 实现默认会覆盖这个。
///code before ....
case "some-custom":
if (arg == null)
{
return null; //RETURN NULL DAMMIT
}
else if (arg is double)
{
var d = (double)arg;
return Math.Round(d, _numberFormatter.NumberDecimalDigits, MidpointRounding.AwayFromZero).ToString(CustomNumericFormat, this);
}
else if (arg is decimal)
{
var d = (decimal)arg;
return Math.Round(d, _numberFormatter.NumberDecimalDigits, MidpointRounding.AwayFromZero).ToString(CustomNumericFormat, this);
}
//code after....
【问题讨论】:
-
String.Format永远不会返回null,因此您需要使用不同的方式。在这种情况下你想显示什么? -
为什么要
string.Format()返回null?这没有意义。 -
@Amy 我正在遍历一个大型数据集以准备表示层 - “格式化”字符串被转储到通用对象字典中。不幸的是,如果什么都没有,表示层的代码希望它为空。我正在处理可空的双精度和小数等问题。显然这不是一个理想的设计……我每天都痛苦地意识到这一点。
-
用
if(str.Length == 0) { str = null; }或类似的方式跟进。 -
@Amy,这也是我的想法......希望 ICustomFormatter 可以开箱即用,但我想我明白了......如果你想把它放入回答,我很擅长。谢谢
标签: c#