经常看到在c#里可以这样使用集合框架:
object o = someHashTable["name"] ;
很是好奇,这样的东西是如何做的,于是看了一下相关资料,发现要实现这样的东西,居然也是用的是属性。于是写了一个简单的类测试一下:
namespace testList ... { public class IntArray ...{ private int[] m_array; private int count; public IntArray(int size) ...{ if (size <= 0) throw new ArgumentOutOfRangeException("大小必须大约0"); count = size; m_array = new int[size]; } public int this[Int32 index] ...{ get ...{ if (index >= 0 && index < count) ...{ return m_array[index]; } else ...{ throw new OverflowException("数组索引越界"); } } set ...{ if (index >= 0 && index < count) ...{ m_array[index] = value; } else ...{ throw new OverflowException("数组索引越界"); } } } }}
要使用这个类,就这样用:
IntArray ia = new IntArray( 100 ); ia[ 1 ] = 50 ;