的String.Format如何处理空值?

人气:1,073 发布:2022-09-10 标签: .net c# string.format

问题描述

在以下code以下,为什么两个的String.Format 通话不行为相同的方式?在第一个,不会抛出异常,但在第二个的 ArgumentNullException 被抛出。

In the following code below, why do the two string.Format calls not behave the same way? In the first one, no exception is thrown, but in the second one an ArgumentNullException is thrown.

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?

推荐答案

我猜在这里,但它看起来是其中的差异超载叫你打。 的String.Format 有多个重载,它只是其中你打。

I'm guessing here, but it looks to be the difference of which overloaded call you're hitting. String.Format has multiple overloads, it's just about which you're hitting.

在第一个例子,它是有意义的你打的String.Format(string,object).

In the first example, it would make sense you're hitting String.Format(string,object).

在第二个例子中b1csw23d.aspx> 的String.Format(字符串,params对象[]) 其中,每个文档,将引发一个 ArgumentNullException 时:

In the second example by providing null you're most likely hitting String.Format(string,params object[]) which, per the documentation, would raise an ArgumentNullException when:

格式或的args为空。

format or args is null.

如果你正在运行.NET4,请尝试使用命名参数:

If you're running .NET4, try using named parameters:

String.Format("Another exception occured: {0}", arg0: null);

为什么一下 params对象[] 超载?大概是因为不是一个对象的方式,以及 PARAMS 工作原理是,你可以通过的或者的每个值在调用一个新的对象的或的传递给它的值的数组。也就是说,以下是在同一个:在

Why is it hitting the params object[] overload? Probably because null isn't an object, and the way params works is that you can pass either each value as a new object in the call or pass it an array of the values. That is to say, the following are one in the same:

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

645