ICustomFormatter使用string.Format返回null

时间:2018-05-23 14:52:09

标签: c#

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

我理解string.Format州的文档:

  

如果参数的值为null,则格式项将替换为   的String.Empty。

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

1 个答案:

答案 0 :(得分:1)

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

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

相反,请使用if(str.Length == 0)跟踪String.Format(...)调用{str = null;或者一些等价物来防止空字符串进入UI。

相关问题