C#索引器简单示例
打開.Net Framework源代碼隨便看幾個類,就會發現索引器的影子。索引器可以被重載,可以接收一個或者多個參數,但是不可以定義為靜態的。可以用關聯數組的方式訪問索引器。
public class Fruit
{
??????? string peach = "a round juicy fruit that has a soft yellow or red skin and a large hard seed in the center, or the tree that this fruit grows on";
??????? string orange = "a round fruit that has a thick orange skin and is divided into parts inside";
??????? string banana = "a long curved tropical fruit with a yellow skin";
??????? string apple = "a hard round fruit that has red, light green, or yellow skin and is white inside ";
??????? public string this[string fruitName]
??????? {
??????????? get
??????????? {
??????????????? switch (fruitName)
??????????????? {
??????????????????? case "peach":
??????????????????????? return peach;
??????????????????? case "orange":
??????????????????????? return orange;
??????????????????? case "banana":
??????????????????????? return banana;
??????????????????? case "apple":
??????????????????????? return apple;
??????????????????? default:
??????????????????????? throw new Exception("wrong fruit name");
??????????????? }
??????????? }
??????????? set
??????????? {
??????????????? switch (fruitName)
??????????????? {
??????????????????? case "peach":
??????????????????????? peach = value;
??????????????????????? break;
??????????????????? case "orange":
??????????????????????? orange = value;
??????????????????????? break;
??????????????????? case "banana":
??????????????????????? banana = value;
???? ???????????????????break;
??????????????????? case "apple":
??????????????????????? apple = value;
??????????????????????? break;
??????????????????? default:
??????????????????????? throw new Exception("wrong fruit name");
??????????????? }
??????????? }
??????? }
??? }
?? ?class Program
??? {
??????? static void Main(string[] args)
??????? {
??????????? Fruit f = new Fruit();
??????????? //關聯數組的方式訪問get方法
??????????? Console.WriteLine(f["peach"]);
??????????? //關聯數組的方式訪問set方法
??????????? f["peach"] = "I like to eat peach.";
??????????? Console.WriteLine(f["peach"]);
??????????? Console.ReadLine();
??????? }
??? }
執行結果:
轉載于:https://www.cnblogs.com/qiuwuyu/archive/2011/08/15/2138650.html
總結
- 上一篇: 添加翻转功能的list类
- 下一篇: C# dynamic使用