索引器类似属性,不过是针对数组的,索引器的使用示例如下所示:
特点:
<1>用this关键字定义索引器
<2>用get,set进行访问
<3>索引器的访问索引可以依据自定的规则,而不是必须是整数
<4>索引器可以被重载
<5>索引器可以有多个形参
推理:
<1>参数类型相同的索引器在类中只能存在一个
<2>若有多个不同索引器,必须索引器的参数不同
接口中的索引器
接口索引器不能使用访问修饰符,不能有函数体;
当类继承多个接口索引器并且索引器的参数相同的时候,需要显式的实现接口的索引器,最终索引器的使用也是只能通过接口来调用,不能通过类的对象来直接调用,示例如下:
namespace ConsoleApplication9Indexer
{
class Class1
{
private string[] Strs = new string[100];
public string this[int i]
{
get { return Strs[i]; }
set { Strs[i] = value; }
}
private int[,] Ints = new int[10,10];
public int this[int i,int j]
{
get { return Ints[i,j]; }
set { Ints[i,j] = value; }
}
}
class Program
{
static void Main(string[] args)
{
Class1 Tc = new Class1();
Tc[1] = "sjkf";
Console.WriteLine(Tc[1]);
Tc[0,0] = 10;
Console.WriteLine(Tc[0,0]);
}
}
}
特点:
<1>用this关键字定义索引器
<2>用get,set进行访问
<3>索引器的访问索引可以依据自定的规则,而不是必须是整数
<4>索引器可以被重载
<5>索引器可以有多个形参
推理:
<1>参数类型相同的索引器在类中只能存在一个
<2>若有多个不同索引器,必须索引器的参数不同
接口中的索引器
接口索引器不能使用访问修饰符,不能有函数体;
当类继承多个接口索引器并且索引器的参数相同的时候,需要显式的实现接口的索引器,最终索引器的使用也是只能通过接口来调用,不能通过类的对象来直接调用,示例如下:
namespace ConsoleApplication9Indexer
{
public interface Inter1
{
string this[int i]
{
get;
set;
}
}
public interface Inter2
{
string this[int j]
{
get;
set;
}
}
public interface Inter3
{
string this[int i]
{
get;
set;
}
}
class Class2 : Inter1,Inter2,Inter3
{
private string[] names = new string[100];
private string[] sexs = new string[100];
private string[] Adds = new string[100];
string Inter1.this[int i]
{
get { return names[i]; }
set { names[i] = value; }
}
string Inter2.this[int j]
{
get { return sexs[j]; }
set { sexs[j] = value; }
}
public string this[int i]
{
get { return Adds[i]; }
set { Adds[i] = value; }
}
}
static void Main(string[] args)
{
Class2 Ts = new Class2();
Inter1 Inters1 = (Inter1)Ts;
Inters1[11] = "whjhd";
Console.WriteLine(Inters1[11]);
Inter2 Inters2 = (Inter2)Ts;
Inters2[67] = "what a fucking day";
Console.WriteLine(Inters2[67]);
}
}