I'm a beginner to c# programming and recently started working on a bachelors degree. What I'm trying to say is, I'm new.
I have marked the place where I have the problem. The problem is that I don't understand why I need to put override in the code at all.
There is 2 var of the type object (first and rest).
public Pair()
{
first = rest = null;
}
public Pair(Object o)
{
first = o;
rest = null;
}
public Object First()
{
return(first);
}
public Object Rest()
{
return(rest);
}
public Pair Connect(Object o)
{
rest = o;
return(this);
}
//Here is the "override string ToString" I don't understand. Why do I need to override this?
public override string ToString()
{
string output = "(";
Pair p = this;
while (p != null) {
if (p.First() == null)
output += "NULL";
else
output += p.First().ToString();
if (p.Rest() is Pair)
p = (Pair)(p.Rest());
else {
if (p.Rest() != null)
output += " . " + rest.ToString();
break;
}
output += " ";
}
output += ")";
return(output);
}
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.
If your question is "why should overriding of ToString
be useful", npinti has the answer.
If your question is "why do I use override
on ToString
but not on other methods", then the answer is: because ToString
is defined on the ancestor classes, and the other methods you are defining aren't. The compiler will complain if you override an inherited method without tagging it with the override
keyword, just as a sanity check to see if that's really what you wanted to do, or if you forgot that this method existed in ancestry.
来源:https://stackoverflow.com/questions/33166889/why-do-i-need-to-override-tostring