在.Net中将一个对象格式化为字符串有以下方式:
1,String.Format(string format, params object[] args)以及几种变形
这种格式化要求args能实现了IFormattable接口
2,string Format(IFormatProvider provider, string format, params object[] args)
这种格式化要求提供一个自定义的格式化功能
3,Object.ToString()
众所周知的,调用了虚方法
下面例子可以显示这几种格式化功能的具体使用时机与实现方法
加入我们要格式化手机号码,众所周知,手机号码是11位的连续整数,但是有时候需要用139-2212-0987的格式进行显示,下面具体的代码:
首先是3个类,公共完成格式化功能:
class ModilePhone:IFormattable
{
public string phone = "15115226678";
string IFormattable.ToString(string format, IFormatProvider formatProvider)
{
if (formatProvider == null)
formatProvider = System.Globalization.CultureInfo.CurrentCulture;
if (format == "G")
return string.Format("From IFormattable[G]:{0}", phone);
return phone;
}
public override string ToString()
{
return "From ToString();";
}
}
class ModilePhoneFormatter : ICustomFormatter
{
string ICustomFormatter.Format(string format, object arg, IFormatProvider formatProvider)
{
ModilePhone tmp = arg as ModilePhone;
if (tmp == null) throw new ArgumentException(string.Format("ModilePhoneFormatter不支持{0}类型的",arg.GetType()));
if (format == "NNN-NNNN-NNNN")
return string.Format("From ICustomFormatter:{0}{1}{2}-{3}{4}{5}{6}-{7}{8}{9}{10}",
tmp.phone[0], tmp.phone[1], tmp.phone[2],
tmp.phone[3], tmp.phone[4], tmp.phone[5], tmp.phone[6],
tmp.phone[7], tmp.phone[8], tmp.phone[9], tmp.phone[10]
);
return "";
}
}
class ModilePhoneFormatProvider : IFormatProvider
{
object IFormatProvider.GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return new ModilePhoneFormatter();
else
return null;
}
}
下面是调用的例子:
ModilePhone tmp = new ModilePhone();
string str0 = string.Format(new ModilePhoneFormatProvider(), "{0:NNN-NNNN-NNNN}", tmp);
//str0 : From ICustomFormatter:151-1522-6678
string str1 = string.Format("{0:G}", tmp);
//str1 : From IFormattable[G]:15115226678
string str2 = tmp.ToString();
//str2 : //From ToString();