Debug.WriteLine() 与 Console.WriteLine() 处理文化的方式不同。为啥?
Posted
技术标签:
【中文标题】Debug.WriteLine() 与 Console.WriteLine() 处理文化的方式不同。为啥?【英文标题】:Debug.WriteLine() versus Console.WriteLine() handles culture differently. Why?Debug.WriteLine() 与 Console.WriteLine() 处理文化的方式不同。为什么? 【发布时间】:2015-01-19 15:31:57 【问题描述】:考虑以下控制台应用程序代码:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
DateTime date = new DateTime(2014, 01, 19);
Console.WriteLine("0", date); // Prints 19/01/2014
Debug.WriteLine("0", date); // Prints 01/19/2014
Debug.WriteLine(date); // Prints 19/01/2014
如 cmets 中所述,Console.WriteLine()
打印 19/01/2014
,而 Debug.WriteLine()
打印 01/19/2014
。
更糟糕的是 - Debug.WriteLine("0", date)
提供与 Debug.WriteLine(date)
不同的输出...
Debug.WriteLine()
是否会忽略线程的文化设置?
有没有办法让Debug.WriteLine()
使用线程的文化设置?还是我必须使用String.Format()
并将结果传递给Debug.WriteLine()
?
(注意:我在 Windows 8.1 64 位 en-GB 上运行此程序,使用 Visual Studio 2013 和 .Net 4.51 以及调试 AnyCPU 版本。)
【问题讨论】:
@TimSchmelter:这与这个问题无关。 @TimSchmelter - 用于更改目的地,损坏(格式化)已经完成。 【参考方案1】:这是明确处理的in the source。
这也是有道理的。 调试输出不应受到最终用户文化的影响;无论代码在哪里运行,您都希望调试日志保持一致。
【讨论】:
好吧,我已经将此标记为答案,但我不同意这个推理。首先,调试输出永远不会出现在最终用户的计算机上(因为它是发布版本,而不是调试版本)。其次,我想要英国格式的日期,所以我不会混淆它们。第三,使用string.Format()
为Debug.WriteLine()
格式化消息是很常见的,因此通过混合使用,您可以获得不同的输出,具体取决于您是否使用string.Format()
构造临时字符串。
更糟糕的是,Debug.WriteLine(date)
给你的结果与Debug.WriteLine("0", date)
不同!
@MatthewWatson 调试输出(希望)永远不会出现在最终用户的 PC 上……但它很容易来自多个开发人员位于多个不同国家/地区的 PC。在那种情况下,我希望所有机器都使用相同的文化设置。
这解释了为什么 Debug 和 Console 不同,但不能解释为什么 Debug.WriteLine("0", date);
与 Debug.WriteLine(date);
不同。你能补充一句吗?
@Ixrec:这实际上是由听众处理的。 referencesource.microsoft.com/#System/compmod/system/… 他们可能直接打电话给ToString()
。【参考方案2】:
你正在使用explicitly ignores the culture的重载通过使用InvariantCulture
:
public static void WriteLine(string format, params object[] args)
TraceInternal.WriteLine(String.Format(CultureInfo.InvariantCulture, format, args));
所有其他重载都没有做任何与文化相关的事情。您可以通过使用采用string
的重载来“解决”此问题:
public static void WriteLine(string message, string category)
TraceInternal.WriteLine(message, category);
通过这样做:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
DateTime date = new DateTime(2014, 01, 19);
var formatedDate = string.Format("0", date);
Console.WriteLine(formatedDate);
Debug.WriteLine(formatedDate);
现在都打印了:
19/01/2014 00:00:00
19/01/2014 00:00:00
【讨论】:
以上是关于Debug.WriteLine() 与 Console.WriteLine() 处理文化的方式不同。为啥?的主要内容,如果未能解决你的问题,请参考以下文章