在.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();