C# string.Format 如何处理空值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13276418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How does string.Format handle null values?
提问by Martin
In the following code below, why do the two string.Formatcalls not behave the same way? In the first one, no exception is thrown, but in the second one an ArgumentNullExceptionis thrown.
在下面的代码中,为什么这两个string.Format调用的行为方式不同?在第一个中,没有抛出异常,但在第二个ArgumentNullException中抛出an 。
static void Main(string[] args)
{
Exception e = null;
string msgOne = string.Format("An exception occurred: {0}", e);
string msgTwo = string.Format("Another exception occurred: {0}", null);
}
Could someone please help me understand the difference between the two?
有人可以帮我理解两者之间的区别吗?
采纳答案by Brad Christie
I'm guessing here, but it looks to be the difference of which overloaded call you're hitting. String.Formathas multiple overloads, it's just about which you're hitting.
我在这里猜测,但它看起来是你正在打哪个重载电话的区别。String.Format有多个重载,这就是您要击中的那个。
In the first example, it would make sense you're hitting String.Format(string,object).
在第一个示例中,您按String.Format(string,object).
In the second example by providing nullyou're most likely hitting String.Format(string,params object[])which, per the documentation, would raise an ArgumentNullExceptionwhen:
在第二个示例中,通过提供null您最有可能达到的情况String.Format(string,params object[]),根据文档,会引发ArgumentNullException何时:
format or args is null.
格式或参数为空。
If you're running .NET4, try using named parameters:
如果您运行的是 .NET4,请尝试使用命名参数:
String.Format("Another exception occured: {0}", arg0: null);
Why is it hitting the params object[]overload? Probably because nullisn't an object, and the way paramsworks is that you can pass eithereach value as a new object in the call orpass it an array of the values. That is to say, the following are one in the same:
为什么会params object[]超载?可能因为null不是对象的方式,以及params工作原理是,你可以通过任何呼叫每个值作为一个新的对象或传递给它的值的数组。也就是说,以下是同一个:
String.Format("Hello, {0}! Today is {1}.", "World", "Sunny");
String.Format("Hello, {0}! Today is {1}.", new Object[]{ "World", "Sunny" })
So it's translating the your statement call to something along the lines of:
因此,它将您的语句调用转换为以下内容:
String format = "Another exception occured: {0}";
Object[] args = null;
String.Format(format, args); // throw new ArgumentNullException();
回答by tmesser
In your first example, you are hitting Format(String, Object), which looks like this when disassembled:
在您的第一个示例中,您正在点击Format(String, Object),反汇编后如下所示:
public static string Format(string format, object arg0)
{
return Format(null, format, new object[] { arg0 });
}
Note the new object[]around that.
注意new object[]周围。
The second one, you are apparently hitting the Format(string, object[])usage, at least that is the one being invoked when I perform the same test. Disassembled, that looks like this:
第二个,您显然正在Format(string, object[])使用,至少当我执行相同的测试时会调用它。拆开来看是这样的:
public static string Format(string format, params object[] args)
{
return Format(null, format, args);
}
So all of these actually get funneled to Format(IFormatProvider, string, object[]). Cool, let's look at the first few lines there:
因此,所有这些实际上都汇集到Format(IFormatProvider, string, object[]). 很酷,让我们看看那里的前几行:
public static string Format(IFormatProvider provider, string format, params object[] args)
{
if ((format == null) || (args == null))
{
throw new ArgumentNullException((format == null) ? "format" : "args");
}
...
}
...welp, there's your problem, right there! The first invocation is wrapping it in a new array, so it's not null. Passing in null explicitly doesn't make it do that, due to the specific instance of Format()that's calling.
...呃,你的问题就在那里!第一次调用是将它包装在一个新数组中,因此它不为空。由于Format()调用的特定实例,显式传入 null 并不会使它这样做。
回答by RossFabricant
The first call gets resolved as a call to Format(object), while the second gets resolved as a call to Format(object[]). Null parameters are handled differently by these different overloads.
第一个调用被解析为对 Format(object) 的调用,而第二个调用被解析为对 Format(object[]) 的调用。这些不同的重载对空参数的处理方式不同。
Overload resolution is described here. The relevant part is that for the second call to Format, an overload of Format(params object[]) gets expanded to Format(object[]), which is preferred to Format(object). The literal null is both an object[] and an object, but object[] is more specific, so that is chosen.
此处描述了重载解决方法。相关的部分是,对于第二次调用 Format,Format(params object[]) 的重载被扩展为 Format(object[]),这优先于 Format(object)。文字 null 既是 object[] 也是 object,但 object[] 更具体,因此选择它。
回答by Jayaseelan
There are two differences which are following:
有以下两个区别:
Here, Null value is assigned.
Exception e = null; string msgOne = string.Format("An exception occurred: {0}", e);Here, Null value cannot be read in string format which means type casting error.
string msgTwo = string.Format("Another exception occurred: {0}", null);
这里,Null 值被赋值。
Exception e = null; string msgOne = string.Format("An exception occurred: {0}", e);这里,不能以字符串格式读取空值,这意味着类型转换错误。
string msgTwo = string.Format("Another exception occurred: {0}", null);
I give you simple example: Here, You cannot read the NULL value as a string format.
我给你一个简单的例子:在这里,你不能将 NULL 值作为字符串格式读取。
string str = null.toString();
回答by Gerard
In case you use an interpolated string ($"", another way to format), the null is ignored, skipped. So
如果您使用内插字符串($"",另一种格式化方式),则忽略、跳过空值。所以
string nullString = null;
Console.WriteLine($"This is a '{nullString}' in a string");
will produce: "This is a '' in a string". Of course you can use the null coalescing operator in case of null to produce the output needed:
将产生:“这是字符串中的 ''”。当然,您可以在 null 的情况下使用 null 合并运算符来生成所需的输出:
string nullString = null;
Console.WriteLine($"This is a '{nullString ?? "nothing"}' in a string");

