为什么需要覆盖ToString? [英] Why do I need to override ToString?
问题描述
我是c#编程的初学者,最近开始攻读学士学位.我想说的是,我是新来的.
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.
类型对象有2个var(第一个和其余个).
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);
}
//这是我不理解的替代字符串ToString".为什么我需要覆盖它?
//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);
}
推荐答案
只要有对象,并且想更改将其表示为字符串的方式,就可以override
ToString
方法.
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.
例如,给定此类:
class Person
{
public int Age { get; set; }
public string Name { get; set; }
}
将Person
类的实例打印到控制台将产生:namespace+classname
,从可读性的角度来看,这是不理想的.
Printing an instance of the Person
class to console would yield: namespace+classname
, which from a readability point of view is not ideal.
将课程更改为此:
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);
}
}
收益率:Name: ... Age: ...
其中的椭圆表示所提供的值.这比以前的方案更具可读性.
Yields: Name: ... Age: ...
where the ellipses denote the values provided. This is more readable than the previous scenario.
这篇关于为什么需要覆盖ToString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!