MST

星途 面试题库

面试题:C#索引器在泛型集合中的应用

假设你要实现一个自定义的泛型集合类,该集合支持通过索引器访问元素,且能在访问越界时抛出自定义异常。请写出该泛型集合类的代码框架,包括必要的构造函数、属性和索引器的实现,并说明如何在不同的索引器重载场景下处理异常。
33.1万 热度难度
编程语言C#

知识考点

AI 面试

面试题答案

一键面试
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++;
    }
}

在不同的索引器重载场景下:

  1. 获取元素:当通过get访问索引器时,如果索引小于0或者大于等于集合当前元素个数Count,则抛出MyCustomException异常,表示索引超出范围。
  2. 设置元素:当通过set访问索引器时,同样检查索引是否小于0或者大于等于Count,如果是则抛出MyCustomException异常,以防止对无效位置进行赋值操作。