索引器是属性的扩展版本吗?
最佳答案
索引器允许像数组一样对类或结构的实例进行索引。索引器类似于属性,只不过它们的访问器采用参数。
class SampleCollection<T>
{
// Declare an array to store the data elements.
private T[] arr = new T[100];
// Define the indexer, which will allow client code
// to use [] notation on the class instance itself.
// (See line 2 of code in Main below.)
public T this[int i]
{
get
{
// This indexer is very simple, and just returns or sets
// the corresponding element from the internal array.
return arr[i];
}
set
{
arr[i] = value;
}
}
}
// This class shows how client code uses the indexer.
class Program
{
static void Main(string[] args)
{
// Declare an instance of the SampleCollection type.
SampleCollection<string> stringCollection = new SampleCollection<string>();
// Use [] notation on the type.
stringCollection[0] = "Hello, World";
System.Console.WriteLine(stringCollection[0]);
}
}
关于c# - C# 中索引器和属性之间有什么关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1768711/