我可以在string.Format中格式化NULL值吗? [英] Can I format NULL values in string.Format?

查看:162
本文介绍了我可以在string.Format中格式化NULL值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否存在用于格式化string.Format中的NULL值的语法,例如Excel使用的

I was wondering if there's a syntax for formatting NULL values in string.Format, such as what Excel uses

例如,使用Excel我可以将格式值指定为 {0:#,000.00;-#,000.00,NULL} ,这意味着如果为正,则将数字值显示为数字格式如果为负,则用括号括起来;如果为空,则为NULL

For example, using Excel I could specify a format value of {0:#,000.00;-#,000.00,NULL}, which means display the numeric value as number format if positive, number format in parenthesis if negative, or NULL if the value is null

string.Format("${0:#,000.00;(#,000.00);NULL}", someNumericValue);

修改

我正在寻找所有数据类型的格式化 NULL / Nothing 值,而不仅仅是数字格式.

I'm looking for formatting NULL/Nothing values for all data types, not just numeric ones.

我的示例实际上是不正确的,因为我错误地认为Excel如果值是NULL就使用了第3个参数,但实际上在值是0时才使用它.我将其保留在那里,因为它是我能想到的最接近的东西我希望做的事.

My example is actually incorrect because I mistakenly thought Excel used the 3rd parameter if the value was NULL, but it's actually used when the value is 0. I'm leaving it in there because it's the closest thing I can think of to what I was hoping to do.

我希望避免使用空合并运算符,因为我正在写日志记录,并且数据通常不是字符串

I am hoping to avoid the null coalescing operator because I am writing log records, and the data is not usually a string

写类似这样的东西会容易得多

It would be much easier to write something like

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

推荐答案

您可以定义,否则返回默认格式的字符串,例如:/p>

You can define a custom formatter that returns "NULL" if the value is null and otherwise the default formatted string, e.g.:

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

这篇关于我可以在string.Format中格式化NULL值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆