[C#]Effective C# 條款五: 總是提供ToString方法

  • 13667
  • 0
  • C#
  • 2011-02-09

[C#]Effective C# 條款五: 總是提供ToString方法

ToString方法昰.NET程式中最常用的方法。除了開發人員直接叫用外,.NET程式在某些情況下也會隱含叫用該方法。

在未做覆寫處理的狀態下,我們呼叫ToString方法時,系統會直接叫用Systrm.Object類別的ToString方法。因此每當我們叫用,返回值多半是類別名稱,像是"System.Object"、"System.Data.DataSet"等較不具識別性的字串。而這樣的字串也多半不是我們想顯示給客戶的,但如果我們不覆寫Object的ToString方法,客戶看到的就將會是這些。

 

讓我們先來看個簡單的例子:


	class Program
    {
        static void Main(string[] args)
        {
            Customer larry=new Customer(){Name="larry"};
            Console.WriteLine(larry);
        }
    }

    public class Customer
    {
        public string Name { get; set; }
        public Decimal Revenue { get; set; }
        public string ContactPhone { get; set; }
    }

 

 

運行結果
image

 

若我們適當的覆寫類別的ToString方法,為類別提供自訂的顯示資訊:


	class Program
    {
        static void Main(string[] args)
        {
            Customer larry = new Customer() { Name = "larry"};
            Console.WriteLine(larry);
        }
    }

    public class Customer
    {
        public string Name { get; set; }
        public Decimal Revenue { get; set; }
        public string ContactPhone { get; set; }

        public override string ToString()
        {
            return string.Format("Customer{{Name = {0}, Revenue = {1}, ContactPhone = {2}}}",Name,Revenue.ToString (),ContactPhone);
        }
    }

 

 

 

 

 

運行後我們可以發現顯示上將變得較具識別性與意義。
image

 

除此之外,在.NET程式中,很多地方都具有隱含叫用ToString的機制。像是Console.WriteLine、String.Format等傳遞Object物件來設定與顯示字串的方法。


	Console.WriteLine(larry.ToString ());
            Console.WriteLine(larry);
            Console.WriteLine (String.Format("{0}", larry));

 

 

 

image

 

甚至是ㄧ些介面的控制項元件也都會隱含叫用ToString。像是ListBox


	public partial class Form1 : Form
    {
        List<Customer> _Customers = new List<Customer>() { new Customer{Name = "larry"}};
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.listBox1.DataSource = _Customers;
        }
    }
    public class Customer
    {
        public string Name { get; set; }
        public Decimal Revenue { get; set; }
        public string ContactPhone { get; set; }

        public override string ToString()
        {
            return string.Format("Customer{{Name = {0}, Revenue = {1}, ContactPhone = {2}}}", Name, Revenue.ToString(), ContactPhone);
        }
    }

 

 

image

 

或是ComboBox等


	public partial class Form1 : Form
    {
        List<Customer> _Customers = new List<Customer>() { new Customer{Name = "larry"}};
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.comboBox1.DataSource = _Customers;
        }
    }
    public class Customer
    {
        public string Name { get; set; }
        public Decimal Revenue { get; set; }
        public string ContactPhone { get; set; }

        public override string ToString()
        {
            return string.Format("Customer{{Name = {0}, Revenue = {1}, ContactPhone = {2}}}", Name, Revenue.ToString(), ContactPhone);
        }
    }

 

image

 

 

 

因此為類別提供適當的ToString方法,不僅有助於使用者辯識。對於開發員來說,在清楚掌握了隱含叫用ToString的機制後,使用覆寫過ToString方法的類別時,也將獲得不少的便利。

 

透過覆寫來撰寫簡單的ToString方法,在大多數的情況下,已經可以滿足我們的需求,但有時候我們會需要功能更強的方法。此時我們可以透過實做IFormattable介面,為類別提供可帶入輸出格式的ToString方法。這邊該介面的實作方法暫且不做介紹,請先自行參考MSDN的IFormattable介面。後續有空將會再回頭補上。