42

我想知道是否有用于格式化 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 }));
4

5 回答 5

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

输出:

$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();
    }
}
于 2011-10-07T15:15:54.120 回答
13

我认为其中没有任何内容可以让您为字符串String.Format指定特定格式。null一种解决方法是使用null-coalescing 运算符,如下所示:

const string DefaultValue = "(null)";

string s = null;
string formatted = String.Format("{0}", s ?? DefaultValue);
于 2011-10-07T15:07:35.407 回答
2

这是你想要的吗?

string test;

测试 ??“空值”

于 2011-10-07T15:07:57.373 回答
1

看起来 .NET 的 String.Format 的行为方式与 Excel 相同,即您可以使用;分隔符来表示正、负和 0 值,但不能为 NULL:http: //msdn.microsoft.com/en-us/library /0c899ak8.aspx#SectionSeparator

您可能只需要手动处理 null 值:

if (myval == null)
    // handle
else
    return String.Format(...);
于 2011-10-07T15:08:45.613 回答
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());
于 2012-06-23T20:32:36.333 回答