C# 如何设计一个在c中使用索引运算符的类#

C# 如何设计一个在c中使用索引运算符的类#,c#,arrays,C#,Arrays,如何设计一个在c#中使用索引运算符的类 我创建了一个行为类似于集合的类 public class CustomCollection<T> { public CustomCollection() { Items = new List<T>(); } private List<T> Items { get; set; } private T[] A { get => Item

如何设计一个在c#中使用索引运算符的类

我创建了一个行为类似于集合的类

public class CustomCollection<T>
{
    public CustomCollection()
    {
        Items = new List<T>();
    }

    private List<T> Items { get; set; }

    private T[] A
    {
        get => Items.ToArray();
        set => Items = value.ToList();
    }

    public void Add(T item)
    {
        Items.Add(item);
    }

    public bool Remove(T item)
    {
        return Items.Remove(item);
    }
}
公共类CustomCollection
{
公共收藏()
{
项目=新列表();
}
私有列表项{get;set;}
私人T[]A
{
get=>Items.ToArray();
set=>Items=value.ToList();
}
公共作废新增(T项)
{
项目。添加(项目);
}
公共布尔删除(T项)
{
返回项目。删除(项目);
}
}
现在我想使用数组操作符来获取其中的值

public static class Program
{
    public static void Main(string[] args)
    {
        var collection = new ConcurrentCollection<int>();

        collection.Add(1);
        collection.Add(5);
        collection.Add(10);

        var item = collection[1]; // <- todo
    }
}
公共静态类程序
{
公共静态void Main(字符串[]args)
{
var collection=新的ConcurrentCollection();
增加第(1)款;
增加(5);
增加(10);

var item=collection[1];//我意识到这个特性被称为索引器:

public class CustomCollection<T>
{
    public CustomCollection()
    {
        Items = new List<T>();
    }

    // Indexer
    public T this[int i]
    {
        get => Items[i];
        set => Items[i] = value;
    }

    private List<T> Items { get; set; }

    private T[] A
    {
        get => Items.ToArray();
        set => Items = value.ToList();
    }

    public void Add(T item)
    {
        Items.Add(item);
    }

    public bool Remove(T item)
    {
        return Items.Remove(item);
    }
}
公共类CustomCollection
{
公共收藏()
{
项目=新列表();
}
//索引器
公共交通工具[int i]
{
get=>Items[i];
集合=>项目[i]=值;
}
私有列表项{get;set;}
私人T[]A
{
get=>Items.ToArray();
set=>Items=value.ToList();
}
公共作废新增(T项)
{
项目。添加(项目);
}
公共布尔删除(T项)
{
返回项目。删除(项目);
}
}
它被称为索引器: