Rac*_*hel 40 c# string.format string-formatting
我想知道是否存在在string.Format中格式化NULL值的语法,例如Excel使用的语法
例如,使用Excel我可以指定格式值{0:#,000.00;-#,000.00,NULL},这意味着如果为正数则将数值显示为数字格式,如果为负数则显示在括号中的数字格式,如果值为null则显示为NULL
string.Format("${0:#,000.00;(#,000.00);NULL}", someNumericValue);
Run Code Online (Sandbox Code Playgroud)
编辑
我正在寻找所有数据类型的格式NULL/ Nothing值,而不仅仅是数字类型.
我的例子实际上是不正确的,因为我错误地认为Excel使用第3个参数,如果值为NULL,但它实际上在值为0时使用.我将它留在那里因为它是我能想到的最接近我的东西希望能做到.
我希望避免使用null合并操作符,因为我正在编写日志记录,并且数据通常不是字符串
写一些类似的东西要容易得多
Log(string.Format("Value1 changes from {0:NULL} to {1:NULL}",
new object[] { oldObject.SomeValue, newObject.SomeValue }));
Run Code Online (Sandbox Code Playgroud)
而不是写
var old = (oldObject.SomeValue == null ? "null" : oldObject.SomeValue.ToString());
var new = (newObject.SomeValue == null ? "null" : newObject.SomeValue.ToString());
Log(string.Format("Value1 changes from {0} to {1}",
new object[] { old, new }));
Run Code Online (Sandbox Code Playgroud)
dtb*_*dtb 33
您可以定义一个自定义格式化程序,"NULL"如果值是null,则返回,否则返回默认格式化字符串,例如:
foreach (var value in new[] { 123456.78m, -123456.78m, 0m, (decimal?)null })
{
string result = string.Format(
new NullFormat(), "${0:#,000.00;(#,000.00);ZERO}", value);
Console.WriteLine(result);
}
Run Code Online (Sandbox Code Playgroud)
输出:
$123.456,78
$(123.456,78)
$ZERO
$NULL
Run Code Online (Sandbox Code Playgroud)
自定义格式器:
public class NullFormat : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type service)
{
if (service == typeof(ICustomFormatter))
{
return this;
}
else
{
return null;
}
}
public string Format(string format, object arg, IFormatProvider provider)
{
if (arg == null)
{
return "NULL";
}
IFormattable formattable = arg as IFormattable;
if (formattable != null)
{
return formattable.ToString(format, provider);
}
return arg.ToString();
}
}
Run Code Online (Sandbox Code Playgroud)
Jim*_*hel 12
我认为没有任何东西String.Format可以让你为null字符串指定特定的格式.解决方法是使用null-coalescing运算符,如下所示:
const string DefaultValue = "(null)";
string s = null;
string formatted = String.Format("{0}", s ?? DefaultValue);
Run Code Online (Sandbox Code Playgroud)