为什么ArrayList没有正确打印?

New*_*ere 2 c# arraylist tostring

ArrayList c = new ArrayList();
c.Add(new Continent("Africa", af));
c.Add(new Continent("America", am));
c.Add(new Continent("Asia", a));
c.Add(new Continent("Oceania", oc));
c.Add(new Continent("Europe", eu));

c.Sort();

for (int i = 0; i < c.Count; i++)
{
Console.WriteLine("{0}", c[i]);
}


output:

TP.Continent
TP.Continent
TP.Continent
TP.Continent
TP.Continent
Run Code Online (Sandbox Code Playgroud)

构造函数很好,因为它排序而不告诉我有错误

第一个元素是一个字符串,另一个是整数.它应该没问题,但由于某种原因它无法正确打印.

Chr*_*ris 7

您正在打印Continent对象,而不是它们各自的部件.您可以将循环更改为:

for (int i=0; i<c.Count; i++)
{
Console.WriteLine("{0}", c[i].name); // Or whatever attributes it has
}
Run Code Online (Sandbox Code Playgroud)

或者您可以在"Continent"对象中添加"ToString"函数以正确打印出来.

这看起来像(在Continent对象中):

public override string ToString()
{
return "Continent: " + attribute; // Again, change "attribute" to whatever the Continent's object has
}
Run Code Online (Sandbox Code Playgroud)


Ed *_* S. 6

你告诉它打印的对象c[i],它调用c[i].ToString(),这rturns类型的名称.

该语言无法深入了解您实际想要打印的此对象的成员.因此,如果您想打印(例如)大陆的名称,则需要将其传递给Console.WriteLine.那,或者您可以覆盖ToString您的类型以返回更有意义的字符串.

另外,几乎没有充分的理由再使用它ArrayList了.更喜欢强类型泛型集合,即

var list = new List<Continent>();
list.Add(new Continent("", whatever)); // ok
list.Add(1); // fails! The ArrayList would allow it however
Run Code Online (Sandbox Code Playgroud)