Sunday, June 15, 2008

C# Array class and IEnumerator

Array這個類別(Class) 實現了 ICloneable, IList, ICollection , IEnumerable 等介面(Interface)
我們可以customize/overload GetEnumerator()
產生符合某些需求的 Enumerators

但是 沒有辦法繼承 Array 來直接衍生我們想要的類別???

"Only the system and compilers can derive explicitly from the Array class. Users should employ the array constructs provided by the language."[ 3 ]

Array's Properties:
Length;
Rank;
?LowerBound;
?UpperBound;

LowerBound 是陣列的起始指標(starting index)
多維陣列的每個維度可以有不同的LowerBound

//===
Array 的一些成員函數(member methods/functions):
public static methods : CreateInstance, Copy, Sort, Reverse, ...
public instance methods: Clone, CopyTo, GetLength, GetType, ...

int[] arr1=new int[10];
Array arr2 = Array.CreateInstance(typeof(int), 10);

string s= "I am a pig!"
Array arr3 = Array.CreateInstance(typeof(char),s.Length);


利用 CreateInstance 方法所產生的陣列擁有較多的功能? 例如 sorting, reversing the elements and more?

//===
IEnumerable: 告訴別人我有提供 foreach 的功能。 這個介面只有一個成員方法 GetEnumerator()
但光有IEnumerable 只是個空殼, 想要 foreach 能正常動作 還必須要『有內涵的』IEnumerator


IEnumerator: 有三個成員(兩個方法 + 一個Properties) Reset(),MoveNext() and Current。


Example

MyKeys: ICollection, IEnumerable

MyKeys myKeys;

foreach(string key in myKeys)
{ doSomething(); }

相當於

0. GetEnumerator() to get the customized IEnumerator, say myEnumerator
myEnumerator= myKeys.GetEnumerator();
myEnumerator.Reset();
1. while( myEnumerator.MoveNext() ){
2. key=myEnumerator.Current; // xxx or myKeys.Current ?
3. doSomething();
4 }


[Q] In C#, it is not strictly necessary for a collection class to inherit from IEnumerable ?


[C]
// Customized IEnumerator usually embedded in the definition of MyKeys
private class MyEnumerator : IEnumerator
{
private int position = -1;
private t;

public MyEnumerator(MyKeys t)
{
this.t = t;
}

public bool MoveNext()
{
if (position < t.Length - 1)
{
position++;
return true;
}
else
{
return false;
}
}

public void Reset()
{
position = -1;
}

// Current property
public object Current
{
get
{
return t[position];
}
}
}





參考連結
[1] http://www.csharphelp.com/archives/archive121.html

[2]
http://www.c-sharpcorner.com/UploadFile/prasadh/Enumerators11132005232321PM/Enumerators.aspx


[3]
http://msdn.microsoft.com/en-us/library/system.array(VS.80).aspx


//================================
三和工作室

No comments: