IFormatProvider、ICustomFormatter、IFormattable

作者:追风剑情 发布于:2018-2-1 20:48 分类:C#

示例: 定制格式化器

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Threading;
  7.  
  8. namespace Test5
  9. {
  10. class Program
  11. {
  12. static void Main(string[] args)
  13. {
  14. StringBuilder sb = new StringBuilder();
  15. sb.AppendFormat(new BoldInt32s(), "{0} {1} {2:M}", "Jeff", 123, DateTime.Now);
  16. Console.WriteLine(sb);
  17. Console.Read();
  18. }
  19. }
  20.  
  21. internal sealed class BoldInt32s : IFormatProvider, ICustomFormatter
  22. {
  23. public Object GetFormat(Type formatType)
  24. {
  25. if (formatType == typeof(ICustomFormatter))
  26. return this;
  27. //使用线程的语言文化信息来获取默认格式
  28. return Thread.CurrentThread.CurrentCulture.GetFormat(formatType);
  29. }
  30.  
  31. public String Format(String format, Object arg, IFormatProvider formatProvider)
  32. {
  33. String s;
  34. IFormattable formattable = arg as IFormattable;
  35. if (formattable == null) s = arg.ToString();
  36. else s = formattable.ToString(format, formatProvider);
  37.  
  38. if (arg.GetType() == typeof(Int32))
  39. return "<B>" + s + "</B>";
  40. return s;
  41. }
  42. }
  43. }

运行测试

111.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号