针对Person的格式化器的实现为:
- class PersonFomatter : IFormatProvider, ICustomFormatter
- {
-
- #region IFormatProvider 成员
-
- public object GetFormat(Type formatType)
- {
- if (formatType == typeof(ICustomFormatter))
- return this;
- else
- return null;
- }
-
- #endregion
-
- #region ICustomFormatter 成员
-
- public string Format(string format, object arg,
- IFormatProvider formatProvider)
- {
- Person person = arg as Person;
- if (person == null)
- {
- return string.Empty;
- }
-
- switch (format)
- {
- case "Ch":
- return string.Format("{0} {1}", person.LastName,
- person.FirstName);
- case "Eg":
- return string.Format("{0} {1}", person.FirstName,
- person.LastName);
- case "ChM":
- return string.Format("{0} {1} : {2}", person.LastName,
- person.FirstName, person.IDCode);
- default:
- return string.Format("{0} {1}", person.FirstName,
- person.LastName);
- }
- }
-
- #endregion
- }
|
一个典型的格式化器应该继承接口IFormatProvider和ICustomFomatter,所以应该像下面这样调用格式化器:
- Person person = new Person() { FirstName = "Jessica", LastName = "Hu",
- IDCode = "NB123" };
- Console.WriteLine(person.ToString());
- PersonFomatter pFormatter = new PersonFomatter();
- Console.WriteLine(pFormatter.Format("Ch", person, null));
- Console.WriteLine(pFormatter.Format("Eg", person, null));
- Console.WriteLine(pFormatter.Format("ChM", person, null));
|
输出为:
- ConsoleApplication4.Person
- Hu Jessica
- Jessica Hu
- Hu Jessica : NB123
|