如何通过参数实现myCollection索引器类数组的灵活大小配置?
解决myCollection固定大小限制的方法
先看你提供的初始代码:
public class myCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { return arr[i]; } set { arr[i] = value; } } }
要打破固定100的容量限制,你可以通过构造函数参数自定义初始容量,还能按需添加动态扩容逻辑,以下是具体实现:
1. 基础方案:自定义初始容量
添加带参数的构造函数,让用户创建实例时指定数组大小,同时保留无参构造兼容原有默认逻辑:
public class myCollection<T> { private T[] arr; // 无参构造,默认容量100,兼容原有代码 public myCollection() : this(100) { } // 带参数构造,支持自定义初始容量 public myCollection(int initialCapacity) { // 校验输入合法性,避免无效容量 if (initialCapacity <= 0) throw new ArgumentOutOfRangeException(nameof(initialCapacity), "初始容量必须大于0"); arr = new T[initialCapacity]; } public T this[int i] { get { // 添加索引越界检查,提升健壮性 if (i < 0 || i >= arr.Length) throw new IndexOutOfRangeException("索引超出集合范围"); return arr[i]; } set { if (i < 0 || i >= arr.Length) throw new IndexOutOfRangeException("索引超出集合范围"); arr[i] = value; } } // 可选:暴露当前容量属性 public int Capacity => arr.Length; }
使用示例:
// 创建容量为10的集合 var smallCollection = new myCollection<string>(10); // 创建容量为200的集合 var largeCollection = new myCollection<int>(200); // 使用默认容量100的集合 var defaultCollection = new myCollection<double>();
2. 进阶方案:自动动态扩容(可选)
如果需要集合像List<T>一样自动扩容,可添加Add方法并在容量不足时扩展数组:
public class myCollection<T> { private T[] arr; private int _count; // 记录实际已添加元素数量 public myCollection() : this(100) { } public myCollection(int initialCapacity) { if (initialCapacity <= 0) throw new ArgumentOutOfRangeException(nameof(initialCapacity), "初始容量必须大于0"); arr = new T[initialCapacity]; _count = 0; } // 索引器仅允许访问已添加的元素范围 public T this[int i] { get { if (i < 0 || i >= _count) throw new IndexOutOfRangeException("索引超出已添加元素范围"); return arr[i]; } set { if (i < 0 || i >= _count) throw new IndexOutOfRangeException("索引超出已添加元素范围"); arr[i] = value; } } // 添加元素,容量不足时自动扩容(默认扩容为当前容量的2倍) public void Add(T item) { if (_count == arr.Length) { int newCapacity = arr.Length * 2; Array.Resize(ref arr, newCapacity); } arr[_count] = item; _count++; } public int Capacity => arr.Length; public int Count => _count; }
这样既可以通过构造函数指定初始容量避免内存浪费,也能在需要时自动扩容,覆盖不同场景需求。
内容的提问来源于stack exchange,提问作者beg-inner
相关产品推荐
相关产品推荐

