Debug.WriteLine()与Console.WriteLine()以不同方式处理文化.为什么?

Mat*_*son 13 .net c# culture date-formatting

请考虑以下Console App代码:

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
Run Code Online (Sandbox Code Playgroud)

如评论中所述,Console.WriteLine()打印19/01/2014Debug.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调试版本运行.)

SLa*_*aks 12

在源中明确处理.

这也是有道理的.
调试输出不应受最终用户文化的影响; 您希望无论代码在何处运行,您的调试日志都是一致的.

  • 好吧,我已将此标记为答案,但我不同意推理.首先,调试输出永远不会出现在最终用户的计算机上(因为它将是发布版本,而不是调试版本).其次,我希望以英国格式提供日期,所以我不会混淆它们.第三,使用`string.Format()`来格式化`Debug.WriteLine()`的消息是很常见的,所以通过混合它你可以获得不同的输出,这取决于你是否使用`string.Format()`来构建临时串. (5认同)
  • 更糟糕的是,`Debug.WriteLine(date)`给出了与Debug.WriteLine("{0}",date)`不同的结果! (2认同)

Yuv*_*kov 10

您正在使用的过载明确地忽略了文化利用InvariantCulture:

public static void WriteLine(string format, params object[] args) 
{
    TraceInternal.WriteLine(String.Format(CultureInfo.InvariantCulture, format, args));
}
Run Code Online (Sandbox Code Playgroud)

所有其他重载都没有做与文化相关的任何事情.您可以通过使用带有string以下内容的重载来"解决"此问题:

public static void WriteLine(string message, string category)
{
    TraceInternal.WriteLine(message, category);
}
Run Code Online (Sandbox Code Playgroud)

通过做这个:

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);
Run Code Online (Sandbox Code Playgroud)

现在两个打印:

19/01/2014 00:00:00 
19/01/2014 00:00:00
Run Code Online (Sandbox Code Playgroud)