C#问题,如何用for语句实现类的实例的遍历

[复制链接]
查看11 | 回复3 | 2009-4-15 18:07:54 | 显示全部楼层 |阅读模式
创建一个学生(Student)类,它有学号(no),姓名(name),C#成绩(CSharpScore)三个成员变量,成员方法自己定义。要求创建一个Student数组,初始化若干名学生数据,然后将其按CSharpScore成绩升序排列,并打印出所有学生的信息。
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace ConsoleApplication1
{

class Program

{

static void Main(string[] args)

{

ArrayList myArrayList = new ArrayList();

Gerbil a = new Gerbil(4);

Gerbil b = new Gerbil(5);

Gerbil c = new Gerbil(6);

Gerbil d = new Gerbil(7);

Gerbil e = new Gerbil(8);

myArrayList.Add(a);

myArrayList.Add(b);

myArrayList.Add(c);

myArrayList.Add(d);

myArrayList.Add(e);

foreach (Gerbil aGerbil in myArrayList)

{

aGerbil.hop();

}

}

}

class Gerbil

{

public int gerbilNumber;

public Gerbil(int Number)

{

gerbilNumber = Number;

}

public void hop()

{

Console.WriteLine(gerbilNumber);

}

}
}
为什么写成using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace ConsoleApplication1
{

class Program

{

static void Main(string[] args)

{

ArrayList myArrayList = new ArrayList();

Gerbil a = new Gerbil(4);

Gerbil b = new Gerbil(5);

Gerbil c = new Gerbil(6);

Gerbil d = new Gerbil(7);

Gerbil e = new Gerbil(8);

myArrayList.Add(a);

myArrayList.Add(b);

myArrayList.Add(c);

myArrayList.Add(d);

myArrayList.Add(e);

for (int i=0;i<myArray.Length;i++)

{

myArray.hop();

}

}

}

class Gerbil

{

public int gerbilNumber;

public Gerbil(int Number)

{

gerbilNumber = Number;

}

public void hop()

{

Console.WriteLine(gerbilNumber);

}

}
}
就错了,那如何用for实现类实例的遍历?
for (int i=0;i<myArray.Length;i++)
{
myArray.hop();
}
打错了,改为for (int i=0;i<myArrayList.Length;i++)
{
myArrayList.hop();
}
错误 1 “System.Collections.ArrayList”不包含“Length”的定义,并且找不到可接受类型为“System.Collections.ArrayList”的第一个参数的扩展方法“Length”(是否缺少 using 指令或程序集引用?) D:\测试\ConsoleApplication16\ConsoleApplication16\Program.cs 24 45 ConsoleApplication16
错误 2 “object”不包含“hop”的定义,并且找不到可接受类型为“object”的第一个参数的扩展方法“hop”(是否缺少 using 指令或程序集引用?) D:\测试\ConsoleApplication16\ConsoleApplication16\Program.cs 26 32 ConsoleApplication16

回复

使用道具 举报

千问 | 2009-4-15 18:07:54 | 显示全部楼层
获取ArrayList的包含元素数目用 ArrayList.CountArrayList中的元素都是object型 要强制转换为你定义的类型for (int i=0;i<myArrayList.Count;i++){((Gerbil)myArrayList).hop();}...
回复

使用道具 举报

千问 | 2009-4-15 18:07:54 | 显示全部楼层
1. ArrayList.Count2. ArrayList 是 object ,必须强制转换((Gerbil)myArrayList).hop();...
回复

使用道具 举报

千问 | 2009-4-15 18:07:54 | 显示全部楼层
首先你的myArray错了,实例的是myArrayList...
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行