看不懂这个书上的例子,在线等待高手进来看一下,从来没有见过这样迷茫的例子.
using System;
public abstract class Shape
{
private string myId;
public Shape(string s)
{
Id=s;
}
public string Id
{
get
{
return myId;
}
set
{
myId=value;
}
}
public abstract double Area
{
get;
}
public virtual void Draw()
{
Console.WriteLine( "Draw Shape Icon ");
}
public override string ToString()
{
return Id + " Area= " + string.Format( "{0:F2} ",Area);
}
}
//正方形类
public class Square:Shape
{
private int mySide;
public Square(int side,string id):base(id)
{
mySide=side;
}
public override double Area
{
get
{
return mySide * mySide;
}
}
public override void Draw()
{
Console.WriteLine( "Draw 4 Siede: " + mySide);
}
}
//测试
public class TestClass
{
public static void Main(string[]args)
{
Square x=new Square(5, "Square #1 ");
Console.WriteLine(x);//不明白为什么能输出: "Square #1 Area= 25.00 "程序当中并没有调用其它的方法啊?
}
}
------解决方案--------------------Console.WriteLine(x);//对于object类型的,就会调用ToString的,你的基类里定义了ToString,就会被调用。这句相当于:
Console.WriteLine(x.ToString());