Using property to access elements of array.
本文於2012/02/09 更新:此需求應為陣列元素唯讀,又能使用索引的方式讀取,故更新此文章。
在網路上有人提出這個問題,想要以屬性(Property)的方式存取陣列元素,而我回應了一個解決方案,主要使用了泛型(Generics)和索引子(Indexer)的方式:
1. 利用泛型先做一個通用的屬性陣列類別
class PropertyArray<T> { private T[] array; public PropertyArray(T[] array) { this.array = array; } public T this[int index] { get { return array[index]; } } }
2. 在需要此功能的類別中加入上面的類別為屬性成員
class Sample { private int[] array1; public PropertyArray<int> Array1 { get; private set; } private float[] array2; public PropertyArray<float> Array2 { get; private set; } public Sample() { array1 = new int[5]; array2 = new float[5]; Array1 = new PropertyArray<int>(array1); Array2 = new PropertyArray<float>(array2); array1[0] = 1; array2[0] = 1.1f; } }
3. 即可以屬性的方式存取陣列元素
static void Main(string[] args) { Sample s = new Sample(); //s.Array1[0] = 1; 無法寫入 //s.Array2[0] = 1.1f; 無法寫入 Console.WriteLine(s.Array1[0]); Console.WriteLine(s.Array2[0]); }