为什么Debug.WriteLine错误地格式化字符串?

我有以下Debug.WriteLine

 Debug.WriteLine("Metadata Version: {0}", version); // update: version is a string 

输出是:

2.0:元数据版本:{0}

为什么字符串格式化?

我没有在MSDN文档中看到任何标识这种格式背后的推理的内容。 我必须执行以下操作才能获得格式正确的输出:

 Debug.WriteLine(string.Format("Metadata Version: {0}", version)); 

由于version是一个string ,因此您需要接受一个类别作为其第二个参数的WriteLine重载 。

虽然有任何数量的黑客可以绕过这种行为(我将在下面添加一些,为了好玩)我个人更喜欢你的解决方案作为明确确保字符串被视为格式字符串的首选方式。

其他一些hacky解决方法:

 Debug.WriteLine("Metadata Version: {0}", version, ""); Debug.WriteLine("Metadata Version: {0}", (object)version); Debug.WriteLine("Metadata Version: {0}", new[] { version }); Debug.WriteLine("Metadata Version: {0}", version, null); 

由于您的version是字符串,因此它使用Debug.WriteLine方法(String,String)重载 。

您可以做几件事来获得正确的结果:

 Debug.WriteLine("Metadata Version: {0}",(object) version); 

或者您可以使用Debug.Print

 Debug.Print("Metadata Version: {0}", version); 

它正在解析对Debug.WriteLine的这个重载的方法调用,它将消息字符串作为其第一个参数,将类别字符串作为第二个参数。

如果将version参数强制转换为System.Object,它将解析为Debug.WriteLine的所需重载 ,它将格式字符串作为其第一个参数,将一个或多个对象作为后续参数。

 Debug.WriteLine("Metadata Version: {0}", (object)version);