您的位置:首页 > 其它

15索引器

2016-12-14 17:01 330 查看
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _15索引器
{
class Program
{
static void Main(string[] args)
{
//int[] numbers = { 1, 2, 3, 4, 5 };

//Console.WriteLine(numbers[2]); //打印:3

//Dictionary<string, int> dic = new Dictionary<string, int>();
//dic.Add("zhangsan",100);
//dic.Add("andu", 60);

//Console.WriteLine(dic["andu"]);//打印 60

Person p = new Person();
//p.Numbers = new int[5] { 3, 6, 7, 8, 9 };
//foreach (var item in p.Numbers)
//{
//    Console.WriteLine(item);
//}

//for (int i = 0; i < p.Numbers.Length; i++)
//{
//    Console.WriteLine(p.Numbers[i]);
//}

//不使用属性访问时,需要使用索引器
//索引器,让对象以索引的方式操作数组
p[0] = 1;
p[1] = 2;
p[2] = 3;

p["zhangsan"] = "好人啊";
p["andu"] = "好人卡";

}
}

class Person
{
private int[] numbers = new int[5];//默认值都为0

public int[] Numbers
{
get
{
return numbers;
}

set
{
numbers = value;
}
}

//索引器必须叫 this
//索引器的写法和属性类似
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]  //类型一样
//{

//}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: