using System;class Point
{
   public int x, y;
   // Default constructor:
   public Point() 
   {
      x = 0;
      y = 0;
   }
   // A constructor with two arguments:
   public Point(int x, int y)
   {
      this.x = x;
      this.y = y;
   }   // Override the ToString method:
   public override string ToString()
   {
      return(String.Format("({0},{1})", x, y));
   }
}class MainClass
{
   static void Main() 
   {
      Point p1 = new Point();
      Point p2 = new Point(5,3);      // Display the results using the overriden ToString method:
      Console.WriteLine("Point #1 at {0}", p1);
      Console.WriteLine("Point #2 at {0}", p2);
   }
}
输出
Point #1 at (0,0)
Point #2 at (5,3)问题: WriteLine输出p1和p2对象时为什么可以调用tostring方法?谢谢!

解决方案 »

  1.   

    打印对象的时候,大概默认就是打印出该对象的toString()
    因为对象继承至OBJECT,所以都有toString()方法
      

  2.   

    WriteLine里面连接对象形成字符串时,调用的不是别的,就是哥哥对象ToString方法。
    如果类没有重写ToString方法,那么就调用类默认从Object哪里继承来的ToString方法。
    类都默认都是从Object继承的,所有都有ToString方法。
      

  3.   

    不是已经覆盖了tostring方法了吗
    public override string ToString()
       {
          return(String.Format("({0},{1})", x, y));
       }