我想知道是否有用于格式化 string.Format 中的 NULL 值的语法,例如 Excel 使用的
例如,使用 Excel,我可以指定格式{0:#,000.00;-#,000.00,NULL}
值
string.Format("${0:#,000.00;(#,000.00);NULL}", someNumericValue);
编辑
我正在寻找所有数据类型的格式NULL
/Nothing
值,而不仅仅是数字类型。
我的示例实际上是不正确的,因为我错误地认为 Excel 在值为 NULL 时使用了第三个参数,但它实际上是在值为 0 时使用的。我将它留在那里是因为它是我能想到的最接近我的东西希望做。
我希望避免使用空合并运算符,因为我正在编写日志记录,并且数据通常不是字符串
写类似的东西会容易得多
Log(string.Format("Value1 changes from {0:NULL} to {1:NULL}",
new object[] { oldObject.SomeValue, newObject.SomeValue }));
比写
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 }));