我想知道在string.Format中是否有一种格式来处理NULL值,就像Excel所使用的那样。
例如,在Excel中,我可以指定一个格式值为{0:#,000.00;-#,000.00,NULL}
,这意味着如果数字是正数,则以数字格式显示,如果为负数,则在括号中以数字格式显示,如果值为空,则显示NULL。
string.Format("${0:#,000.00;(#,000.00);NULL}", someNumericValue);
编辑
我正在寻找格式化所有数据类型(不仅仅是数字类型)的NULL
/Nothing
值的方法。
我的示例实际上是错误的,因为我错误地认为Excel在值为NULL时使用第三个参数,但实际上它是在值为0时使用。我保留它因为这是我所能想到的最接近我希望完成的内容。
我希望避免使用null合并运算符,因为我正在编写日志记录,而数据通常不是字符串。
编写类似下面这样的内容将会更加容易:
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 }));
null
(在 Visual Basic 中为Nothing
)还是0
(零)? - dtbnull
/Nothing
。 - Rachel