“ this [int index]”是什么意思? [英] What is the meaning of "this [int index]"?

查看:685
本文介绍了“ this [int index]”是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,我们具有以下接口:

In C# we have the following interface:

public interface IList<T> : ICollection<T>, IEnumerable<T>, IEnumerable
{
    T this [int index] { get; set; }
    int IndexOf (T item);
    void Insert (int index, T item);
    void RemoveAt (int index);
}

我不懂这行

T this [int index] { get; set; }

这是什么意思?

推荐答案

这是在接口上定义的索引器。这意味着您可以获取设置 list [index] IList< T>中的$ c>列表 int索引

That is an indexer defined on the interface. It means you can get and set the value of list[index] for any IList<T> list and int index.

文档:接口中的索引器(C#编程指南)

考虑 IReadOnlyList< T> 接口:

public interface IReadOnlyList<out T> : IReadOnlyCollection<T>, 
    IEnumerable<T>, IEnumerable
{
    int Count { get; }
    T this[int index] { get; }
}

该接口的示例实现:

public class Range : IReadOnlyList<int>
{
    public int Start { get; private set; }
    public int Count { get; private set; }
    public int this[int index]
    {
        get
        {
            if (index < 0 || index >= Count)
            {
                throw new IndexOutOfBoundsException("index");
            }
            return Start + index;
        }
    }
    public Range(int start, int count)
    {
        this.Start = start;
        this.Count = count;
    }
    public IEnumerable<int> GetEnumerator()
    {
        return Enumerable.Range(Start, Count);
    }
    ...
}

现在您可以写像这样的代码:

Now you could write code like this:

IReadOnlyList<int> list = new Range(5, 3);
int value = list[1]; // value = 6

这篇关于“ this [int index]”是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆