/// <summary>
/// 泛型类(最多容纳100个T)
/// </summary>
/// <typeparam name="T"></typeparam>
public class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int index]
{
get
{
//检查索引范围
return (index < 0 || index > 100) ? arr[0] : arr[index];
}
set
{
//检查索引范围
if (index >= 0 && index <= 100)
{
arr[index] = value;
}
}
}
}
public class SampleCollection
{
private int[] arr = new int[100];
public int this[int index]
{
get
{
//检查索引范围
return (index < 0 || index > 100) ? arr[0] : arr[index];
}
set
{
//检查索引范围
if (index >= 0 && index <= 100)
{
arr[index] = value;
}
}
}
}
调用方式
SampleCollection<string> Samples = new SampleCollection<string>();
Samples[0] = "a";
Samples[2] = "c";
Samples[101] = "d";
SampleCollection Samples2 = new SampleCollection();
Samples2[0] = 2;
Samples2[2] = 3;
Console.ReadKey();