定制字符串Format

   class Program 
{
static void Main()
{
StringBuilder sb = new StringBuilder();
IFormatProvider f=new BoldInt();
BoldInt b = new BoldInt();
sb.AppendFormat(f, "{0} {1} {2:M}", "Xiaobai", 21, DateTime.Now);
Console.WriteLine(sb.ToString());
Console.ReadKey();
}
}
sealed class BoldInt : IFormatProvider, ICustomFormatter
{
#region ICustomFormatter 成员

string ICustomFormatter.Format(string format, object arg, IFormatProvider formatProvider)
{
string s;
IFormattable formattable = arg as IFormattable;
if (formattable == null) s = arg.ToString();
else s = formattable.ToString(format, formatProvider);
if (arg.GetType() == typeof(Int32))
return "<B>"+s+"</B>";
if(arg.GetType()==typeof(DateTime))
return "<DateTime>"+s+"</DateTime>";
if (arg.GetType() == typeof(String))
return "<String>" + s + "</String>";
return s;
}

#endregion
#region IFormatProvider 成员
object IFormatProvider.GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter)) return this;
return Thread.CurrentThread.CurrentCulture.GetFormat(formatType);
}
#endregion
}
原文地址:https://www.cnblogs.com/smailxiaobai/p/2289237.html