索引器:
作用:让对象具有快速访问元素的能力.索引器和数组的区别:
1.索引器的索引类型不限定为整数.
2.索引器可以有重载
3.索引器可以看成是特殊的属性,特殊的方法,具备set和get访问器.
索引器和属性的区别:
1.索引器是以函数名this来标示.属性是任意名字,但是首字母大写.
2.索引器可以重载,但是属性不能
3.索引器有参数,但是属性没有
4.索引器不能用static修饰
using System;
namespace 索引器
{
class Test
{
//定义一个数组
private int[] intArray = new int[10];
//定义索引器
public int this [int index]
{
//存
set {
if (index >= 0 && index < 10) {
intArray [index] = value;
}
}
//取
get{
if(index<=0 && index >= 10){
return 0;
}else{
return intArray[index];
}
}
}
//索引器重载
public string this [string index]{
get{
return "你好";
}
}
}
class MainClass
{
public static void Main (string[] args)
{
int[] intArray = new int[2];
intArray [0] = 100;
intArray [1] = 200;
Test t = new Test ();
t [0] = 100;
t [1] = 200;
Console.WriteLine (t [0]);
Console.WriteLine (t [1]);
Console.WriteLine (t [2]);
Console.WriteLine (t ["xx"]);
}
}
}