面试题答案
一键面试using System;
public class MyCustomException : Exception
{
public MyCustomException(string message) : base(message)
{
}
}
public class CustomGenericCollection<T>
{
private T[] items;
public CustomGenericCollection(int capacity)
{
items = new T[capacity];
}
public int Count { get; private set; }
public T this[int index]
{
get
{
if (index < 0 || index >= Count)
{
throw new MyCustomException("索引超出范围");
}
return items[index];
}
set
{
if (index < 0 || index >= Count)
{
throw new MyCustomException("索引超出范围");
}
items[index] = value;
}
}
public void Add(T item)
{
if (Count == items.Length)
{
// 可以实现自动扩容逻辑
throw new InvalidOperationException("集合已满");
}
items[Count] = item;
Count++;
}
}
在不同的索引器重载场景下:
- 获取元素:当通过
get
访问索引器时,如果索引小于0或者大于等于集合当前元素个数Count
,则抛出MyCustomException
异常,表示索引超出范围。 - 设置元素:当通过
set
访问索引器时,同样检查索引是否小于0或者大于等于Count
,如果是则抛出MyCustomException
异常,以防止对无效位置进行赋值操作。