【问题标题】:What is the meaning of "this [int index]"?“this [int index]”是什么意思?
【发布时间】:2015-05-28 15:56:42
【问题描述】:

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

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; }

什么意思?

【问题讨论】:

  • 这意味着如果您调用myList[myInteger] = foo;T foo = myList[myInteger],您将获得一个额外的方法get_Itemset_Item 来执行内部工作,其中foo 的类型是T。跨度>

标签: c# .net interface


【解决方案1】:

那是一个索引器。所以你可以像数组一样访问实例;

See MSDN documentation.

【讨论】:

    【解决方案2】:

    那是在接口上定义的索引器。这意味着您可以将getsetlist[index] 的值用于任何IList&lt;T&gt; listint index

    文档:Indexers in Interfaces (C# Programming Guide)

    考虑IReadOnlyList&lt;T&gt; 接口:

    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);
        }
        ...
    }
    

    现在您可以编写如下代码:

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

    【讨论】:

    • 你能告诉我这辆出租车有什么帮助吗
    猜你喜欢
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 2018-10-29
    • 1970-01-01
    • 2015-08-28
    • 2011-06-05
    • 1970-01-01
    • 2011-06-20
    相关资源
    最近更新 更多