通过反射修改私有字段
using System;using System.Collections.Generic;using System.Data;using System.Globalization;using System.Reflection;using System.Runtime.CompilerServices;using System.Threading;namespace ConsoleApplication1{ class Program { static void Main(string[] args) { //输出未修改前本地化设置的ToString结果 Console.WriteLine(DateTime.Now); //还真没测出DateTimeFormatInfo.CurrentInfo是NULL的情况,但是预防一下 if (DateTimeFormatInfo.CurrentInfo != null) { var type = DateTimeFormatInfo.CurrentInfo.GetType(); var field = type.GetField("generalLongTimePattern", BindingFlags.NonPublic | BindingFlags.Instance); //我怂!! if (field != null) field.SetValue(DateTimeFormatInfo.CurrentInfo, "yyyy-MM-dd HH:mm:ss"); } //输出修改后的结果 Console.WriteLine(DateTime.Now); //修改默认时间ToString格式的的另一种方式 [多线程失效] //Thread.CurrentThread.CurrentCulture = (CultureInfo)CultureInfo.CurrentCulture.Clone(); //DateTimeFormatInfo.CurrentInfo.ShortDatePattern = "yyyy-MM-dd"; //DateTimeFormatInfo.CurrentInfo.LongTimePattern = "HH:mm:ss"; //Console.WriteLine(DateTime.Now.ToString()); //var thread = new Thread(() => Console.WriteLine(DateTime.Now)); //thread.Start(); ////同上 //var action = new Action(() => Console.WriteLine(DateTime.Now)); //action.BeginInvoke(null, null); Console.ReadLine(); } }}
评论