[英]Can I format NULL values in string.Format?
我想知道是否存在在string.Format中格式化NULL值的语法,例如Excel使用的语法
例如,使用Excel我可以指定格式值{0:#,000.00;-#,000.00,NULL}
,这意味着如果为正数则显示数字值,如果为负数则显示在括号中的数字格式,如果是,则为NULL value为null
string.Format("${0:#,000.00;(#,000.00);NULL}", someNumericValue);
编辑
我正在寻找所有数据类型的格式化NULL
/ Nothing
值,而不仅仅是数字类型。
我的例子实际上是不正确的,因为我错误地认为Excel使用第3个参数,如果值为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
,则返回"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();
}
}
我不认为String.Format
中有任何东西可以让你为null
字符串指定一个特定的格式。 解决方法是使用null-coalescing运算符 ,如下所示:
const string DefaultValue = "(null)";
string s = null;
string formatted = String.Format("{0}", s ?? DefaultValue);
这是你想要的吗?
string test;
测试? “空值”
它看起来像String.Format for .NET的行为方式与Excel相同,即你可以使用;
正,负和0值的分隔符,但不是NULL: http : //msdn.microsoft.com/en-us/library/0c899ak8.aspx#SectionSeparator 。
您可能只需要手动处理空值:
if (myval == null)
// handle
else
return String.Format(...);
您可以使用扩展方法:
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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.