![](/img/trans.png)
[英]String.Format vs int.ToString in regards to iCustomFormatter issue
[英]ICustomFormatter return null with string.Format
我有一个自定义格式化程序,如果arg
为null,则返回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....
您的自定义格式器会返回一个要插入的字符串,该字符串将插入模式持有人( {0:some-custom}
)。 它没有返回最终结果。 在字符串中插入null等同于该字符串。
String.Format()
由文档定义,因此它始终返回string
。 即使您可以更改它,也将违反其合同。 那不是最理想的。
相反,请遵循String.Format(...)
调用if(str.Length == 0){str = null; }或其他等效项,以防止空字符串进入用户界面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.