Console.WriteLine(ArrayList)输出错误
我正在尝试打印各种foreach循环的ArrayList的内容,但我唯一得到的是String + System.Collections.ArrayList。
例如,以下代码:
ArrayList nodeList = new ArrayList(); foreach (EA.Element element in elementsCol) { if ((element.Type == "Class") || (element.Type == "Component") || (element.Type == "Package")) { nodeList.Add(element); } Console.WriteLine("The nodes of MDG are:" + nodeList); //stampato a schermo la lista dei nodi nel MDG finale
我得到的输出是:
The nodes of MDG are:System.Collections.ArrayList
请有人告诉我为什么?
你必须循环遍历arraylist才能获得它的价值……
foreach(var item in nodeList) { Console.WriteLine("The nodes of MDG are:" + item); }
这将工作..
更新:
使用element而不是nodelist
Console.WriteLine("The nodes of MDG are:" + element);
首先,没有充分的理由在C#中使用ArrayList。 您应该至少使用System.Collections.Generic.List
,甚至在这里它们可能是更具体的数据结构。 永远不要使用像ArrayList这样的无类型集合。
其次,当您将对象传递给Console.Writeline()时,它只调用该对象的.ToString()方法。
ArrayList不会覆盖从基础对象类型inheritance的.ToString()方法。
基本对象类型上的.ToString()实现只是打印出对象的类型。 因此,您发布的行为正是预期的行为。
我不知道选择背后的原因是不要为数组和其他序列类型重写.ToString(),但简单的事实是,如果你想要打印出数组中的各个项,你必须编写代码迭代项目并自己打印。
转换为nodeList
字符串只会调用nodeList.ToString()
,它会生成您看到的输出。 相反,您必须迭代数组并打印每个单独的项目。
或者你可以使用string.Join
:
Console.WriteLine("The nodes of MDG are:" + string.Join(",", nodeList));
顺便说一句,没有理由(或借口)在C#2及更高版本中仍然使用ArrayList
– 如果你没有将遗留代码切换到List
StringBuilder builder = new StringBuilder(); foreach (EA.Element element in elementsCol) { if ((element.Type == "Class") || (element.Type == "Component") || (element.Type == "Package")) { builder.AppendLine(element.ToString()); } } Console.WriteLine("The nodes of MDG are:" + builder.ToString());
这会调用nodeList.ToString()。 在列表中的每个元素上运行ToString()并将它们连接在一起会更有意义:
Console.WriteLine("The nodes of MDG are:" + string.Join(", ", nodeList));
我使用以下代码获得了我想要的输出:
using System.IO using (StreamWriter writer = new StreamWriter("C:\\out.txt")) { Console.SetOut(writer); } Console.WriteLine("the components are:"); foreach (String compName in componentsList) { Console.WriteLine(compName); }
componentsList是我想要打印的arraylist。
感谢大家的帮助