我会让我的 3 个视图模型实现一个通用接口 IFormattablePerson 具有用于计算全名的字段并依赖于 String.Format
这允许通过在自定义格式化程序中添加新的字符串格式来非常方便地扩展显示。
这将导致类似:
视图模型必须实现的通用接口:
public interface IFormattablePerson: IFormattable
{
string FirstName{get;set;}
string LastName{get;set;}
}
在每个视图模型中,相同的 ToString() 实现永远不会改变
public string ToString(string format, IFormatProvider formatProvider)
{
if (formatProvider == null)
return ToString(format, new FormatProviderIFormattablePerson());
else
return (formatProvider.GetFormat(typeof(IFormattablePerson)) as ICustomFormatter).Format(format, this, formatProvider);
}
这将 FormatProvider 和 CustomFormatter 用于 IFormattablePerson。然后你只需要在 CustomFormatter 中添加和实现新的格式
public class FormatProviderIFormattablePerson : IFormatProvider
{
// String.Format calls this method to get an instance of an
// ICustomFormatter to handle the formatting.
public object GetFormat(Type service)
{
if (service == typeof(IFormattablePerson))
{
return new CustomFormatterIFormattablePerson();
}
else
{
return null;
}
}
}
public class CustomFormatterIFormattablePerson : ICustomFormatter
{
public string Format(string format, object arg, IFormatProvider provider)
{
if (string.IsNullOrEmpty(format))
format = "full";
if (arg is IFormattablePerson)
{
IFormattablePerson t = (IFormattablePerson) arg;
switch (format)
{
case "f":
return t.FirstName;
case "l":
return t.LastName;
case "full":
default:
return string.Format("{0} {1}",
t.FirstName,
t.LastName).Trim();
}
}
if (arg is IFormattable)
return string.Format(String.Format("{{0:{0}}}",format), arg);
else
return arg.ToString();
}
}