如何在C#中显示arraylist的元素 [英] How to display the elemens of arraylist in C#
问题描述
我编写了以下代码:
Hi,
I have written the following code:
using System;
using System.Collections;
namespace ArrayList1
{
class Program
{
ArrayList a1 = new ArrayList();
static void Main(string[] args)
{
Program objProg = new Program();
objProg.a1.Add(10);
objProg.a1.Add(5.67);
objProg.a1.Add("abcde");
objProg.a1.Add(''c'');
foreach(int i in objProg.a1)
Console.WriteLine("i");
}
}
}
我遇到运行时异常.有身体请引导我.
Zulfi.
我尝试过的事情:
我进行了网络搜索,但是代码仍然无法正常工作.
I am getting run-time exception. Some body please guide me.
Zulfi.
What I have tried:
I did web search but still code not working.
推荐答案
尝试:
class Program
{
static ArrayList a1 = new ArrayList();
static void Main(string[] args)
{
a1.Add(10);
a1.Add(5.67);
a1.Add("abcde");
a1.Add('c');
foreach (object i in a1)
{
Console.WriteLine(i);
}
}
}
重点:
-在Main
方法中创建程序类的新实例以能够访问类成员不是一个好习惯.
-a1
类变量必须是静态的,才能从静态方法访问.
-在foreach
循环中,不能将i
声明为int
,因为您的数组列表不只包含整数值.可以匹配整数,双精度型,字符串和字符的常见类型是object
.
-Console.WriteLine("i");
将打印字母i
而不是变量i
的值.
Key points:
- Creating a new instance of the program class in the Main
method to be able to access a class member is not a good practice.
- a1
class variable has to be static to be accessed from a static method.
- In the foreach
loop, you cannot declare i
as an int
since your arraylist does not hold only integer values. The common type which can match an integer, a double, a string and a character is an object
.
- Console.WriteLine("i");
will print the letter i
instead of the value of the variable i
.
这篇关于如何在C#中显示arraylist的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!