- 类似与数组取值,数组赋值
- 索引器都可以用函数代替
- 方便阅读
使用例子
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _14_索引器
{
internal class Test
{
private string[] name = new string[10];
public string this[int index]
{
get
{
return name[index];
}
set
{
name[index] = value;
}
}
}
}
在Test类内定义字符串数组,定义索引器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _14_索引器
{
internal class Week
{
private string[] days = { "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat", "Sun" };
public int GetDay(string day)
{
int i = 0;
foreach(string temp in days)
{
if (temp == day) return i+1;
i++;
}
return -1;
}
public int this[string day]
{
get
{
return GetDay(day);
}
}
}
}
测试
using System;
namespace _14_索引器
{
internal class Program
{
static void Main(string[] args)
{
//数组索引
int[] array = { 34, 67, 432, 4, 32 };
Console.WriteLine(array[1]);
//例子1
Test test = new Test();
test[0] = "张三";
test[1] = "李四";
Console.WriteLine(test[0]);
Console.WriteLine(test[1]);
//索引器具体例子,
Week week = new Week();
Console.WriteLine(week.GetDay("Thurs"));
Console.WriteLine(week["Thurs"]);
}
}
}