改善C#程序的157个建议(连载13)

发表于:2011-11-02 09:52

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:陆敏技    来源:51Testing软件测试网采编

  针对Person的格式化器的实现为:

  1. class PersonFomatter : IFormatProvider, ICustomFormatter  
  2. {  
  3.  
  4.     #region IFormatProvider 成员  
  5.  
  6.     public object GetFormat(Type formatType)  
  7.     {  
  8.         if (formatType == typeof(ICustomFormatter))  
  9.             return this;  
  10.         else  
  11.             return null;  
  12.     }  
  13.  
  14.     #endregion  
  15.  
  16.     #region ICustomFormatter 成员  
  17.  
  18.     public string Format(string format, object arg,  
  19.         IFormatProvider formatProvider)  
  20.     {  
  21.         Person person = arg as Person;  
  22.         if (person == null)  
  23.         {  
  24.             return string.Empty;  
  25.         }  
  26.  
  27.         switch (format)  
  28.         {  
  29.             case "Ch":  
  30.                 return string.Format("{0} {1}", person.LastName,  
  31.                     person.FirstName);  
  32.             case "Eg":  
  33.                 return string.Format("{0} {1}", person.FirstName,  
  34.                     person.LastName);  
  35.             case "ChM":  
  36.                 return string.Format("{0} {1} : {2}", person.LastName,  
  37.                     person.FirstName, person.IDCode);  
  38.             default:  
  39.                 return string.Format("{0} {1}", person.FirstName,  
  40.                     person.LastName);  
  41.         }  
  42.     }  
  43.  
  44.     #endregion  
  45. }

  一个典型的格式化器应该继承接口IFormatProvider和ICustomFomatter,所以应该像下面这样调用格式化器:

  1. Person person = new Person() { FirstName = "Jessica"LastName = "Hu",  
  2.     IDCode = "NB123" };  
  3. Console.WriteLine(person.ToString());  
  4. PersonFomatter pFormatter = new PersonFomatter();  
  5. Console.WriteLine(pFormatter.Format("Ch", person, null));  
  6. Console.WriteLine(pFormatter.Format("Eg", person, null));  
  7. Console.WriteLine(pFormatter.Format("ChM", person, null)); 

  输出为:

  1. ConsoleApplication4.Person  
  2. Hu Jessica  
  3. Jessica Hu  
  4. Hu Jessica : NB123

32/3<123>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号