我能否在string.Format中格式化NULL值?

42

我想知道在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(零)? - dtb
@dtb 我正在寻找格式化 null / Nothing - Rachel
@JimMischel 抱歉,我想的是用第三个参数格式化 Excel 的 NULL 值。实际上应该是零值。我会更新我的问题,但我会保留 Excel 示例,因为这是我能想到的最接近我要找的东西。 - Rachel
5个回答

34

您可以定义一个自定义格式化程序,如果值为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);
}

输出:

$123.456,78
$(123.456,78)
$ZERO
$NULL

自定义格式化程序:

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();
    }
}

谢谢,这正是我所希望的工作方式!你刚刚让我的生活变得更加轻松了 :) - Rachel
这对我不起作用。我正在编写一个 JsonValueFormatter,但 null 值从未进入 Format 方法。如果我执行 string.Format(formatter, "Test: {0}, {1}, {2}", true, 10, null, "Hello"),它会返回 Test: true, 10, , "Hello" - Nick Sotiros

12

我认为在 String.Format 中没有任何东西可以让您为 null 字符串指定特定格式。 一个解决方法是使用 null-coalescing 运算符 ,像这样:

const string DefaultValue = "(null)";

string s = null;
string formatted = String.Format("{0}", s ?? DefaultValue);

请看我的更新问题。我希望避免使用??,因为数据通常不是字符串。 - Rachel
1
@Rachel:请看我的更新回复。你没有理由将空值合并运算符限制在字符串上。 - Jim Mischel
10
好的,但我希望您将默认值设置为"NULL",即使数据类型是数字或日期。我不能使用someNumber ?? "NULL",因为字符串"NULL"someNumber不属于相同的数据类型。 - Rachel

2

这是您想要的吗?

string test;

测试 ?? "NULL"


请查看我的更新问题。我希望避免使用 ??,因为数据通常不是字符串。 - Rachel

1

0
你可以使用扩展方法:
 public static string ToDataString(this string prm)
   {
       if (prm == null)
       {
           return "NULL";
       }
       else
       {
           return "'" + prm.Replace("'", "''") + "'";
       }
   }

然后在你的代码中可以这样做:

string Field1="Val";
string Field2=null;

string s = string.Format("Set Value:{0}, NullValue={1}",Field1.ToDataString(), Field2.ToDataString());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接