MSDN索引器与属性的对比
MSDN索引器与属性的对比
索引器允许您按照与数组相同的方式对类、结构或接口进行索引。
索引器允许类或结构的实例按照与数组相同的方式进行索引。索引器类似于属性,不同之处在于它们的访问器采用参数。
class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
get
{
return arr[i];
}
set
{
arr[i] = value;
}
}
}
// This class shows how client code uses the indexer
class Program
{
static void Main(string[] args)
{
SampleCollection<string> stringCollection = new SampleCollection<string>();
stringCollection[0] = "Hello, World";
System.Console.WriteLine(stringCollection[0]);
}
}
索引器概述
· 索引器使得对象可按照与数组相似的方法进行索引。
· get 访问器返回值。set 访问器分配值。
· this 关键字用于定义索引器。
· value 关键字用于定义由 set 索引器分配的值。
· 索引器不必根据整数值进行索引,由您决定如何定义特定的查找机制。
· 索引器可被重载。
· 索引器可以有多个形参,例如当访问二维数组时。
索引器类型及其参数类型必须至少如同索引器本身一样是可访问的。
索引器的签名由其形参的数量和类型组成。它不包括索引器类型或形参名。如果在同一类中声明一个以上的索引器,则它们必须具有不同的签名。
索引器值不归类为变量;因此,不能将索引器值作为 ref 或 out 参数来传递。
要为索引器提供一个其他语言可以使用的名字,
[System.Runtime.CompilerServices.CSharp.IndexerName("TheItem")]
public int this [int index] // Indexer declaration
{
}
索引器可在 interface上声明。接口索引器的访问器与类索引器的访问器具有以下方面的不同:
· 接口访问器不使用修饰符。
· 接口访问器没有体。
// Indexer on an interface:
public interface ISomeInterface
{
// Indexer declaration:
int this[int index]
{
get;
set;
}
}
// Implementing the interface.
class IndexerClass : ISomeInterface
{
private int[] arr = new int[100];
public int this[int index] // indexer declaration
{
get
{
// Check the index limits.
if (index < 0 || index >= 100)
{
return 0;
}
else
{
return arr[index];
}
}
set
{
if (!(index < 0 || index >= 100))
{
arr[index] = value;
}
}
}
}
class MainClass
{
static void Main()
{
IndexerClass test = new IndexerClass();
// Call the indexer to initialize the elements #2 and #5.
test[2] = 4;
test[5] = 32;
for (int i = 0; i <= 10; i++)
{
System.Console.WriteLine("Element #{0} = {1}", i, test[i]);
}
}
}
索引器与属性类似。除下表中显示的差别外,为属性访问器定义的所有规则同样适用于索引器访问器。
|
属性 |
索引器 |
|
允许调用方法,如同它们是公共数据成员。 |
允许调用对象上的方法,如同对象是一个数组。 |
|
可通过简单的名称进行访问。 |
可通过索引器进行访问。 |
|
可以为静态成员或实例成员。 |
必须为实例成员。 |
|
属性的 get访问器没有参数。 |
索引器的 get 访问器具有与索引器相同的形参表。 |
|
属性的 set 访问器包含隐式 value 参数。 |
除了 value 参数外,索引器的 set 访问器还具有与索引器相同的形参表。 |

浙公网安备 33010602011771号