在下面的代码中,为什么两个string.Format
调用的行为方式不同?在第一个中,不会引发异常,但是在第二个中,会引发ArgumentNullException
。
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);
}
有人可以帮我理解两者之间的区别吗?
我在这里猜测,但这似乎是您遇到的重载呼叫的区别。 String.Format
具有多个重载,这与您要击中的重载有关。
在第一个示例中,您要按String.Format
才有意义。
在第二个示例中,通过提供String.Format(string,object)
,您很可能会击中String.Format(string,object)
,根据文档,在以下情况下,这会引发null
:
format或args为空。
如果正在运行.NET4,请尝试使用命名参数:
String.Format(string,params object[])
为什么会达到String.Format(string,params object[])
超载?可能是因为ArgumentNullException
不是对象,并且String.Format("Another exception occured: {0}", arg0: null);
的工作方式是您可以在调用或中将每个值作为新对象传递给[[任一,并将值的数组传递给它。也就是说,以下是params object[]
:
null
因此,它将您的声明调用翻译为以下内容:
params
String.Format("Hello, {0}! Today is {1}.", "World", "Sunny");
String.Format("Hello, {0}! Today is {1}.", new Object[]{ "World", "Sunny" })
注意周围的String format = "Another exception occured: {0}"; Object[] args = null; String.Format(format, args); // throw new ArgumentNullException();
。[第二个,您显然正在使用
Format(String, Object)
用法,至少那是我执行相同测试时所调用的用法。拆卸后,看起来像这样:
public static string Format(string format, object arg0) { return Format(null, format, new object[] { arg0 }); }
因此,所有这些实际上都集中到了new object[]
。很酷,让我们看看那里的前几行:
Format(string, object[])
...很高兴,您的问题就在那里!第一次调用将其包装在新数组中,因此它不是null。由于要调用的 public static string Format(string format, params object[] args)
{
return Format(null, format, args);
}
的特定实例,因此显式传递null并不能做到这一点。