本文實例講述了C#中foreach原理以及模擬的實現方法,分享給大家供大家參考。具體如下:
public int Count { get { return names.Length; } } //可以通過對象訪問此屬性
public string this[int index] //定義一個索引器
{
get { return names[index]; }
}
public IEnumerator GetEnumerator()
{
return new MyClass(names); //實際上通過此方法就是返回一個可以實現循環的類的對象
// 用他的對象來移動索引
}
}
public class MyClass :IEnumerator
{
public MyClass(string[] names) //一個參數的構造函數,用來和要遍歷的類的進行關聯
{
name = names;
}
private string[] name; //用此字段來存放接收過來的數組
int index = -1;
public object Current //獲取當前索引的元素的值
{
get
{
if (index<0) //準備狀態是-1,開始循環了在MoveNext中加1
{
return null;
}
else
{
return name[index];
}
}
}
public bool MoveNext()
{
++index; //每調用此方法就將索引往下+1
if (index<name.Length)
{
return true;
}
else
{
return false;
}
}
public void Reset()
{
index=-1;
}
}
在主方法里面:
希望本文所述對大家的C#程序設計有所幫助。
新聞熱點
疑難解答