我是 C# 编程的初学者,最近开始攻读学士学位。我想说的是,我是新来的。
有问题的地方我已经标出来了。问题是我根本不明白为什么我需要在代码中放置覆盖。
有 2 个对象类型的变量(第一个和其余)。
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);
}
//这里的“override string ToString”我没看懂。为什么我需要覆盖它?
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);
}
最佳答案
只要您有一个对象并且希望更改它作为字符串的表示方式,您就可以覆盖
ToString
方法。
这通常用于格式化选项,因此当您将项目打印到控制台时,您可以控制它们如何显示给查看它们的人。
例如,给定这个类:
class Person
{
public int Age { get; set; }
public string Name { get; set; }
}
将 Person
类的实例打印到控制台会产生:namespace+classname
,从可读性的角度来看这并不理想。
将类更改为:
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: ...
其中省略号表示提供的值。这比之前的场景更具可读性。
关于c# - 为什么我需要覆盖 ToString?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33166889/