"this [int index]"是什么意思?
What is the meaning of "this [int index]"?
在 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; }
这是什么意思?
那是一个索引器。所以你可以像访问数组一样访问实例;
那是在接口上定义的索引器。这意味着您可以 get
和 set
任何 IList<T> list
和 int index
.
的 list[index]
的值
文档:Indexers in Interfaces (C# Programming Guide)
考虑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);
}
...
}
现在你可以这样写代码了:
IReadOnlyList<int> list = new Range(5, 3);
int value = list[1]; // value = 6
在 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; }
这是什么意思?
那是一个索引器。所以你可以像访问数组一样访问实例;
那是在接口上定义的索引器。这意味着您可以 get
和 set
任何 IList<T> list
和 int index
.
list[index]
的值
文档:Indexers in Interfaces (C# Programming Guide)
考虑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);
}
...
}
现在你可以这样写代码了:
IReadOnlyList<int> list = new Range(5, 3);
int value = list[1]; // value = 6