You override
the ToString
method whenever you have an object and you would like to change the way it is represented as a string.
This is usually done for formatting options, so that when you print items to console you have control over how they are displayed to who ever is viewing them.
For instance, given this class:
class Person
{
public int Age { get; set; }
public string Name { get; set; }
}
Printing an instance of the Person
class to console would yield: namespace+classname
, which from a readability point of view is not ideal.
Changing the class to this:
class Person
{
public int Age { get; set; }
public string Name { get; set; }
public override string ToString()
{
return String.Format("Name: {0} Age: {1}.", this.Name, this.Age);
}
}
Yields: Name: ... Age: ...
where the ellipses denote the values provided. This is more readable than the previous scenario.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…