In. net, System. object. toString () is one of the most commonly used methods. The ToString () method is defined as virtual in the Object class, and the Object class gives it a default implementation:
1 public virtual string ToString ()
2 {
3 return this. GetType (). ToString ();
4}
In. Net, the original class or struct, such as int and DateTime, all override it to make it return more valuable values, rather than type names. It is very convenient to program and debug the ToString () method. However, after all, a class has only one ToString () method, which cannot satisfy our diversified needs. Many classes overload ToString. As follows:
1 string dateString = DateTime. Now. ToString ("yyyy"); // 2009
2 string intString = 10. ToString ("d4"); // 0010
Int and DateTime all implement the ToString (string format) method, which greatly facilitates our use.
We should also provide a reasonable ToString () rewrite for our own defined types. If we can provide another ToString (string format), it will make our later work easier. Types:
1 public class People
2 {
3 private List <People> friends = new List <People> ();
4
5 public int Id {get; set ;}
6 public string Name {get; set ;}
7 public DateTime Brithday {get; set ;}
8 public People Son {get; set ;}
9 public People [] Friends {get {return friends. ToArray ();}}
10
11 public void AddFriend (People newFriend)
12 {
13 if (friends. Contains (newFriend) throw new ArgumentNullException ("newFriend"