您的位置:首页 > 编程语言

[作业10-11]1.编写一个类立方体Cub,让其实现IEnumarable接口,细节是令其可以遍历迭代长宽高,并做一个客户代码验证。

2009-10-12 15:35 926 查看
Cub.cs代码:

using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;

namespace ConsoleApplication1
{

public class Cub : IEnumerable //声明立方体Cub类继承IEnumerable接口!
{
int length; //声明长度!
int width; //声明宽度!
int height; //声明高度!

public void cub(int length, int width, int height) //声明构造函数,并用长宽高签名!
{
this.length = length;
this.width = width;
this.height = height;
}

#region IEnumerable 成员

public IEnumerator GetEnumerator()
{
return new CubEnumerator(this); //返回当前枚举对象!
}

#endregion
public int this[uint i] //索引器!
{
get
{
switch (i)
{
case 0:
return length;
case 1:
return width;
case 2:
return height;
default:
throw new IndexOutOfRangeException(
"Attempt to retrieve Vector element" + i);
}
}
set
{
switch (i)
{
case 0:
length = value;
break;
case 1:
width = value;
break;
case 2:
height = value;
break;
default:
throw new IndexOutOfRangeException(
"Attempt to set Vector element" + i);
}
}
}

}

#region enumerator class
public class CubEnumerator : IEnumerator //声明CubEnumerator类,并继承接口IEnumerator!
{
Cub theCub; // Cub object that this enumerato refers to
int location; // which element of theCub the enumerator is currently referring to

public CubEnumerator(Cub theCub)
{
this.theCub = theCub;
location = -1;
}

public bool MoveNext()
{
++location;
return (location > 2) ? false : true;
}

public object Current
{
get
{
if (location < 0 || location > 2)
throw new InvalidOperationException(
"The enumerator is either before the first element or " +
"after the last element of the Vector");
return theCub[(uint)location];
}
}

public void Reset()
{
location = -1;
}
}
#endregion
}

Program.cs代码:

using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Cub c = new Cub(); //实例化一个Cub类!
c.cub(2, 3, 4); //初始化长、宽、高的值!

foreach (int temp in c) //迭代集合c!
{
foreach (int next in c) //迭代集合c!
{
Console.Write(" " + next);
}
Console.WriteLine(temp);
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐