索引器允许类或结构的实例就像数组一样进行索引。
索引器类似于 属性,不同之处在于它们的访问器采用参数。
例如:
class SuoYinQi<T>
{
private T[] arr = new T(10);
public this [int i]
{
get { return arr; }
set {arr=value; }
}
}
class Program
{
static void Main(string[] args)
{
SuoYinQi<string> str = new SuoYinQi<string>();
str[0]="abc";
Console.WriteLine(str[0]); //打印出abc
Console.ReadKey();
}
}
使用索引器可以用类似于数组的方式为对象建立索引。
get 访问器返回值。
set 访问器分配值。
this 关键字用于定义索引器。
value 关键字用于定义由 set 索引器分配的值。
索引器不必根据整数值进行索引,由您决定如何定义特定的查找机制。
索引器可被重载。
索引器可以有多个形参,例如当访问二维数组时。
索引器的脚标可以为其它类型参数,例如:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 索引器
{
class Program
{
static void Main(string[] args)
{
SYQ<string> str = new SYQ<string>();
str["t1"] = "hello";
str["t2"] = "World";
str["t3"] = "c#";
Console.WriteLine(str["t1"]);
Console.WriteLine(str["t2"]);
Console.WriteLine(str["t3"]);
Console.ReadKey();
}
}
class SYQ<T>
{
private T t1;
private T t2;
public T this[string str]
{
get
{
switch(str)
{
case "t1" :
return t1 ;
case "t2" :
return t2;
default: return default(T);
}
}
set
{
switch (str)
{
case "t1":
t1 = value;
break;
case"t2":
t2 = value;
break;
//default: Console.WriteLine("不存在"); break;
}
}
}
}
}
class Person {
PRivate string firstname;
public string FirstName {
get {return firstname;}
set {firstname = value;}
}
}
属性声明可以如下编码:
Person p = new Person();
p.FirstName = "Lamont";
Console.WriteLine (p.FirstName);
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]);
}
}