在 C# 中循环遍历 ArrayList 的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12626258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 23:56:15  来源:igfitidea点击:

looping through the values of an ArrayList in C#

c#arraylistosc

提问by mheavers

I'm trying to figure out what sort of information these messages contain that are being streamed via OSC. The messages are being stored to an ArrayList. Here is the code:

我试图弄清楚这些消息包含哪些类型的信息是通过 OSC 流式传输的。消息被存储到一个 ArrayList。这是代码:

public void OSCMessageReceived(OSC.NET.OSCMessage message){ 
        string address = message.Address;
        ArrayList args = message.Values;
}

How do I loop through the values of the arrayList args to output its contents?

如何遍历 arrayList args 的值以输出其内容?

采纳答案by Aghilas Yakoub

you can try with this code

你可以试试这个代码

foreach(var item in args )
{
  Console.WriteLine(item);
}

回答by Gromer

ArrayList al = new ArrayList(new string[] { "a", "b", "c", "d", "e" });
foreach (var item in al)
{
    Console.WriteLine(item);
}

You can also use a forloop.

您也可以使用for循环。

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

回答by DanM7

You can use a simple forloop:

您可以使用一个简单的for循环:

for (i = 0; i < args.Count; i++)
{
    Console.WriteLine(args[i].ToString());
}

Check out this link herefor more info on the C# ArrayList object.

在此处查看此链接以获取有关 C# ArrayList 对象的更多信息。

回答by Alex Gelman

Unless you know the type of objects in the ArrayList, your only option is to call the ToString()method on each item.

除非您知道 ArrayList 中的对象类型,否则您唯一的选择是ToString()对每个项目调用该方法。

If you do know the type of objects, you can cast them to the appropriate type and then to print the content in a more intelligent way.

如果您确实知道对象的类型,则可以将它们转换为适当的类型,然后以更智能的方式打印内容。

回答by Michael Kaufmann

Both foreach()and for(int i = 0;...)scroll through all entries of the ArrayList. However it seems that foreach()scrolls through them in the order in which they were added to the ArrayList. With for(int i = 0;...)I observed (Visual Studio 2005) that this is not necessarily true. I experienced in one case that when the objects added to the ArrayList were simple int's it was the case. However when the added objects were of a complex class type the scroll order no longer corresponded to the order in which they had been added to the ArrayList.

两者的foreach();对于(... INT I = 0)通过该ArrayList所有条目滚动。但是,foreach()似乎按照它们添加到 ArrayList 的顺序滚动浏览它们。使用for(int i = 0;...)我观察到(Visual Studio 2005)这不一定是真的。我曾经历过一种情况,当添加到 ArrayList 的对象是简单的int时,情况就是这样。然而,当添加的对象是复杂的类类型时,滚动顺序不再对应于它们被添加到 ArrayList 的顺序。