c#編程指南(六) 類索引器(Class Indexer)

來源:互聯網
上載者:User

類索引器,可以使得你使用數組一樣的方式來訪問類的資料。

這種訪問多見於數組,列表,詞典,雜湊表的快捷訪問。

 

實際上寫法很簡單,寫成:public T1 this[T2 i]

 

代碼如下:

 

 1 using System;
2  using System.Collections.Generic;
3  using System.Linq;
4  using System.Text;
5  using System.Drawing;
6
7  namespace Indexer
8 {
9 public class Test
10 {
11 private List<string> _lstTest = new List<string>();
12
13 public List<string> Items
14 {
15 get { return _lstTest; }
16 set { _lstTest = value; }
17 }
18
19 public string this[int i]
20 {
21 get {
22 if ((i >= 0) && (i < _lstTest.Count)) return _lstTest[i];
23 else throw new IndexOutOfRangeException("the error index is " + i);
24 }
25
26 set {
27 if ((i >= 0) && (i < _lstTest.Count)) _lstTest[i] = value;
28 else throw new IndexOutOfRangeException("the error index is " + i);
29 }
30 }
31
32 public string this[string s] { get { return "Test Return " + s; } }
33
34
35 public string this[Color c] { get { return c.ToString(); } }
36 }
37
38
39 class Program
40 {
41 static void Main(string[] args)
42 {
43 Test test = new Test();
44
45 test.Items.Add("test1");
46 test.Items.Add("test2");
47 test.Items.Add("test3");
48 for (int i = 0; i < test.Items.Count; i++)
49 {
50 Console.WriteLine(test[i]);
51 }
52
53 Console.WriteLine("----------------------------------------------------------");
54 test[0] = "test4";
55 for (int i = 0; i < test.Items.Count; i++)
56 {
57 Console.WriteLine(test[i]);
58 }
59
60 Console.WriteLine("----------------------------------------------------------");
61 Console.WriteLine(test["香山飄雪"]);
62
63
64 Console.WriteLine("----------------------------------------------------------");
65 Console.WriteLine(test[Color.BlueViolet]);
66 }
67 }
68 }

 

 

很簡單吧,

第一個,我定義了一個可讀可寫的以int為參數的索引器。

第二個,我定義了一個可讀的以string為參數的索引器。

第三個,比較搞怪了,我定義了一個color參數的索引器。

 

呵呵,是很簡單吧!!

SkyDriver代碼下載:下載

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.