【问题标题】:ICustomFormatter return null with string.FormatICustomFormatter 使用 string.Format 返回 null
【发布时间】: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#


【解决方案1】:

您的自定义格式化程序返回一个要插入到模式持有者 ({0:some-custom}) 的位置的字符串。它没有返回最终结果。将 null 插入字符串与该字符串相同。

String.Format() 由文档定义,因此它总是返回string。即使您可以更改它,也将违反其合同。这是次优的。

相反,在String.Format(...) 调用之后使用 if(str.Length == 0) { str = null; } 或类似的东西来防止空字符串进入 UI。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-11
    • 2015-11-08
    • 2020-11-03
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多