相关疑难解决方法(0)

我可以在string.Format中格式化NULL值吗?

我想知道是否存在在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)

c# string.format string-formatting

40
推荐指数
2
解决办法
3万
查看次数

标签 统计

c# ×1

string-formatting ×1

string.format ×1