是否可以覆盖ToString()方法以输出列表? 这是我的代码
namespace CircularClass
{
class InfinitelyCircular
{
public class RatsInAShip
{
public string RatBreed;
public string RatWeight;
public string RatAge;
public bool HasChildren;
public List<RatsInAShip> RatChildren;
public override string ToString()
{
return String.Format("RatBreed:{0}\n RatWeight:{1}\n RatAge:{2}\n HasChildren:{3}",RatBreed, RatWeight, RatAge, HasChildren);
}
}
static void Main(string[] args)
{
var mu = new RatsInAShip()
{
RatAge = "100",
RatBreed = "RexRat",
RatWeight = "200",
HasChildren = true,
RatChildren = new List<RatsInAShip>()
};
for (var i = 0; i < 3; i++)
{
var cu = new RatsInAShip()
{
RatAge = "100",
RatBreed = "DwarfRat"+i,
RatWeight = "200",
HasChildren = false
};
mu.RatChildren.Add(cu);
}
//Output
Console.WriteLine(String.Format("{0}, {1}", mu.RatBreed, mu.RatChildren[0]));
}
}
}
如何覆盖ToString()以输出列表中的所有子项?
答案 0 :(得分:4)
看起来你已经覆盖了类上的ToString()方法......所以...使用StringBuilder和for / foreach循环来构造输出字符串?
答案 1 :(得分:3)
也许您可以在foreach循环中输出子项,如下所示:
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("RatBreed:{0}\n RatWeight:{1}\n RatAge:{2}\n HasChildren:{3}\n",RatBreed, RatWeight, RatAge, HasChildren);
foreach (RatsInAShip rat in RatChildren)
{
sb.AppendFormat("\tRat Child: {0}\n", rat);
}
return sb.ToString();
}
我没有编译过这个,所以如果我犯了错误,请纠正我。 [编辑]现在编译......:)
答案 2 :(得分:2)
输出列表?如在,返回一个列表?没有。原因有二:
ToString()
表示它返回一个字符串。返回任何其他内容将非常不直观,并且会引起代码支持问题。答案 3 :(得分:1)
您无法更改已覆盖方法的返回类型。
您需要编写自己的方法来返回列表:
public IList<string> ToList()
{
// your code that returns a list of strings
}
答案 4 :(得分:1)
是:
public override string ToString()
{
string result = "";
if(RatChildren != null)
foreach(var x in RatChildren)
result += String.Format("RatBreed:{0}\n RatWeight:{1}\n RatAge:{2}\n HasChildren:{3}", x.RatBreed, x.RatWeight, x.RatAge, x.HasChildren);
return result;
}
答案 5 :(得分:0)
您可以像现在一样覆盖ToString
。您可以遍历列表的元素以输出您想要的字符串。