代码改变世界

Effective C# 学习笔记(五) 最好重载你所创建类的ToString()方法

2011-07-02 23:15  小郝(Kaibo Hao)  阅读(429)  评论(0编辑  收藏  举报

通过重载ToString() 方法可以很好的将你的对象以格式化的形式展现给其他程序员

尤其在Windows form, Web Form, HTML 等界面展现时可以提供编程的灵活度

// supported formats:

// substitute n for name.

// substitute r for revenue

// substitute p for contact phone.

// Combos are supported: nr, np, npr, etc

// "G" is general.

string System.IFormattable.ToString(string format,

IFormatProvider formatProvider)

{

if (formatProvider != null)

{

ICustomFormatter fmt = formatProvider.GetFormat(

this.GetType()) as ICustomFormatter;

if (fmt != null)

return fmt.Format(format, this, formatProvider);

}

switch (format)

{

case "r":

return Revenue.ToString();

case "p":

return ContactPhone;

case "nr":

return string.Format("{0,20}, {1,10:C}",

Name, Revenue);

case "np":

return string.Format("{0,20}, {1,15}",

Name, ContactPhone);

case "pr":

return string.Format("{0,15}, {1,10:C}",

ContactPhone, Revenue);

case "pn":

return string.Format("{0,15}, {1,20}",

ContactPhone, Name);

case "rn":

return string.Format("{0,10:C}, {1,20}",

Revenue, Name);

case "rp":

return string.Format("{0,10:C}, {1,20}",

Revenue, ContactPhone);

case "nrp":

return string.Format("{0,20}, {1,10:C}, {2,15}",

Name, Revenue, ContactPhone);

case "npr":

return string.Format("{0,20}, {1,15}, {2,10:C}",

Name, ContactPhone, Revenue);

case "pnr":

return string.Format("{0,15}, {1,20}, {2,10:C}",

ContactPhone, Name, Revenue);

case "prn":

return string.Format("{0,15}, {1,10:C}, {2,15}",

ContactPhone, Revenue, Name);

case "rpn":

return string.Format("{0,10:C}, {1,15}, {2,20}",

Revenue, ContactPhone, Name);

case "rnp":

return string.Format("{0,10:C}, {1,20}, {2,15}",

Revenue, Name, ContactPhone);

case "n":

case "G":

default:

return Name;

}

}