ICustom格式化程序返回带有字符串的空值.格式



我有一个自定义格式化程序,如果arg为空,则返回 null。但是,string.Format(MyCustomFormatProvider, {0:some-custom}, null)返回一个空字符串。有什么办法可以解决这个问题吗?

我了解string.Format状态的文档:

如果参数的值为 null,则格式项将替换为 字符串.空。

我希望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....

好吧,您的自定义格式化程序返回一个字符串,以插入模式持有人({0:some-custom}(所在的位置。 它不会返回最终结果。 在字符串中插入 null 与该字符串相同。

String.Format()由文档定义,因此它始终返回一个string。 即使你可以改变这一点,也会违反其合同。 这是次优的。

相反,按照String.Format(...)调用,使用 if(str.长度 == 0( { str = null; } 或一些等效项,以防止空字符串进入 UI。

最新更新