【问题标题】:Can I format NULL values in string.Format?我可以在 string.Format 中格式化 NULL 值吗?
【发布时间】:2011-12-03 02:15:12
【问题描述】:

我想知道在string.Format中是否有格式化NULL值的语法,比如Excel使用什么

例如,使用 Excel,我可以指定格式值{0:#,000.00;-#,000.00,NULL},这意味着如果为正,则将数值显示为数字格式,如果为负,则在括号中显示数字格式,如果值为 null,则显示为 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 }));

【问题讨论】:

  • null(Visual Basic 中为Nothing)还是0(零)?
  • @dtb 我正在寻找格式化null / Nothing
  • @JimMischel 抱歉,我在想 Excel 使用第三个参数格式化 NULL 值。它实际上是零。我将更新我的问题,但我将 Excel 示例留在那里,因为它是我能想到的最接近我正在寻找的东西。

标签: c# string-formatting string.format


【解决方案1】:

您可以定义一个custom formatter,如果值为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();
    }
}

【讨论】:

  • 谢谢你,这正是我希望它起作用的方式!你让我的生活变得轻松了很多:)
  • 这对我不起作用。我正在写一个 JsonValueFormatter 并且空值永远不会进入 Format 方法。如果我这样做string.Format(formatter, "Test: {0}, {1}, {2}", true, 10, null, "Hello"),它会返回Test: true, 10, , "Hello"
【解决方案2】:

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

const string DefaultValue = "(null)";

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

【讨论】:

  • 查看我更新的问题。我希望避免使用??,因为数据通常不是字符串
  • @Rachel:查看我的更新回复。没有理由需要将 null 合并运算符限制为字符串。
  • 是的,但我希望默认值为"NULL",即使数据类型是数字或日期。我不能使用someNumber ?? "NULL",因为字符串"NULL"someNumber 的数据类型不同
【解决方案3】:

这是你想要的吗?

string test;

测试?? “空”

【讨论】:

  • 查看我更新的问题。我希望避免使用??,因为数据通常不是字符串
【解决方案4】:

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

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

if (myval == null)
    // handle
else
    return String.Format(...);

【讨论】:

    【解决方案5】:

    您可以使用扩展方法:

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

    【讨论】:

      猜你喜欢
      • 2013-06-22
      • 2010-11-28
      • 1970-01-01
      • 2011-06-20
      • 1970-01-01
      • 1970-01-01
      • 2015-06-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多