C#基础:编写一个类立文体,让其实现IEnumarable接口,细节是令其可以遍历迭代长宽高
今天去上课!又学到不少东西!
晚上加班把学到的一点东西,与大家分享一下!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Cub cub = new Cub(1, 2, 3);
foreach (int vorter in cub) //foerach循环结构!
{
Console.WriteLine(vorter);
}
}
}
public class Cub : IEnumerable //继承IEnumerable, IEnumarable接口
{
int Length;
int Wicth;
int Herht; //定义三个int类型的变量!
public Cub(int length, int Wicth, int Herht)
{
this.Length = length;
this.Wicth = Wicth;
this.Herht = Herht;
}
#region IEnumerable 成员
public IEnumerator GetEnumerator()
{
return new CubEnumera(this);
}
#endregion
public int this[uint i] //索引!
{
get {
switch (i)
{
case 0: return Length;
case 1: return Wicth;
case 2: return Herht;
default: throw new IndexOutOfRangeException(
"Attempt to retrieve Vector element" + i);
}
}
set
{
switch (i)
{
case 0: Length = value; break;
case 1: Wicth = value; break;
case 2: Herht = value; break;
default:
throw new IndexOutOfRangeException(
"Attempt to set Vector element" + i);
}
}
}
}
public class CubEnumera : IEnumerator
{
Cub cub;
int num;
public CubEnumera(Cub cub)
{
this.cub = cub;
num = -1;
}
#region IEnumerator 成员
public object Current
{
get {
if(num < 0 || num > 2)
throw new NotImplementedException("");
return cub[(uint)num];
}
}
public bool MoveNext()
{
++num;
return (num > 2) ? false:true ;
}
public void Reset()
{
throw new NotImplementedException();
}
#endregion
}
}
后记:
刚写完上面代码!虽然知道怎么写了!但还不知道应该怎么用!
注释也不应该怎么去写!
希望大家明白的能指点一下!
感谢了!
先睡觉了!
明天还早班!