今天看到一段代码:
namespace ConsoleApplication2
{
class Person
{
public string Name { get; set; }
public int Age { get; set; }
//重写object类的ToString()方法,string类是sealed类,不能override.
public override string ToString()
{
return "Person: " + Name + " " + Age;
}
}
class Program
{
static void Main(string[] args)
{
Person person1 = new Person { Name = "John", Age = 12 };
Console.WriteLine(person1); //会自动调用ToString()方法。
Console.WriteLine(person1.Name.ToString());
Console.WriteLine(person1.ToString());
}
}
}
Console.WriteLine(object)时,会自动调用ToString()方法的。因为string是sealed类,所以被inhrets.不能被inhrets就不能override它的ToString()方法了。