Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

c# - Why do I need to override ToString?

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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...