在C#中,是否可以覆盖DateTime.ToString()函数?

3
我希望覆盖默认的DateTime.ToSting()函数行为,以便我可以自动添加CultureInfo
最终结果是,如果有人像这样使用该函数:
DateTime.Now.ToString("g");

我可以这样让它工作:
DateTime.Now.ToString("g", new CultureInfo("en-US"));

这是一个在.NET 4 Framework中运行的多线程应用程序,我不希望在每个线程上都设置它。


这是一个在.NET 4中的多线程应用程序。我不想在每个线程上都设置它。 - David
你不想每次都设置文化信息吗?你是这个意思吗? - Yuval Itzchakov
我更喜欢不在每个线程上设置它。如果能够覆盖此函数,那将更好。 - David
你总是使用 "en-us" 作为你的文化吗? - Yuval Itzchakov
不会,但是所有线程将使用相同的文化 - David
2个回答

1
你可以更改当前线程的 CultureInfo,这将导致所需的更改。根据 MSDN,DateTime.ToString 方法使用从当前文化派生的格式信息。有关详细信息,请参见 CurrentCulture
因此,您可以简单地编辑用于创建其他线程的线程中的 CultureInfo.CurrentCulture 属性,这将使您达到所需的行为。
MSDN 多线程和 AppDomains 的示例:
using System;
using System.Globalization;
using System.Threading;

public class Info : MarshalByRefObject
{
   public void ShowCurrentCulture()
   {
      Console.WriteLine("Culture of {0} in application domain {1}: {2}",
                        Thread.CurrentThread.Name,
                        AppDomain.CurrentDomain.FriendlyName,
                        CultureInfo.CurrentCulture.Name);
   }
}

public class Example
{
   public static void Main()
   {
      Info inf = new Info();
      // Set the current culture to Dutch (Netherlands).
      Thread.CurrentThread.Name = "MainThread";
      CultureInfo.CurrentCulture = CultureInfo.CreateSpecificCulture("nl-NL");
      inf.ShowCurrentCulture();

      // Create a new application domain.
       AppDomain ad = AppDomain.CreateDomain("Domain2");
       Info inf2 = (Info) ad.CreateInstanceAndUnwrap(typeof(Info).Assembly.FullName, "Info");
       inf2.ShowCurrentCulture();                       
   }
}
// The example displays the following output: 
//       Culture of MainThread in application domain ChangeCulture1.exe: nl-NL 
//       Culture of MainThread in application domain Domain2: nl-NL

你可以尝试通过Microsoft FakesMoles等类似工具来覆盖方法的使用,但这并不是真正推荐的做法。

0

DateTime是一个密封的结构体,因此无法被继承。实现这一点的一种方法是使用扩展:

public static class MyDateTimeExtension
{

    public static string ToMyCulture(this DateTime dt, CultureInfo info)
    {
         ...
    }
}

DateTime timeTest = DateTime.Now;
var myTimeString = timeTest.ToMyCulture(new CultureInfo("en-US"));

这不会改变已经编写到应用程序中的类的行为。 - VMAtm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接