using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 索引
{
class Program
{
static void Main(string[] args)
{
Person per = new Person();
//per.Numbers = new int[] { 1, 2, 3, 4, 5 };
//for(int i =0; i < per.Numbers.Length;i++)
//{
// Console.WriteLine(per.Numbers[i]);
//}
//以索引方式访问
per[0] = 2;
per[1] = 3;
per["Mao"] = "good";
per["Dog"] = "bad";
for (int i = 0; i < per.Numbers.Length; i++)
{
Console.WriteLine(per[i]);
}
Console.WriteLine(per["Mao"]);
Console.ReadKey();
}
}
class Person
{
private int[] numbers = new int[5];
public int[] Numbers
{
get
{
return numbers;
}
set
{
numbers = value;
}
}
//创建索引器,让对象以索引的方式操作数组
public int this[int index]
{
get
{
return numbers[index];
}
set
{
numbers[index] = value;
}
}
//键值对,前面是键,后面是值
Dictionary<string, string> dic = new Dictionary<string, string>();
public string this[string index]
{
get
{
return dic[index];
}
set
{
dic[index]= value;
}
}
Dictionary<int, string> dic2 = new Dictionary<int, string>();
//public string this[int index] { }
//与public int this[int index]只有返回值不一样,不能重载
}
}