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方法?谢谢!
{
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方法?谢谢!
因为对象继承至OBJECT,所以都有toString()方法
如果类没有重写ToString方法,那么就调用类默认从Object哪里继承来的ToString方法。
类都默认都是从Object继承的,所有都有ToString方法。
public override string ToString()
{
return(String.Format("({0},{1})", x, y));
}