新聞中心
一、 索引器定義:
目前成都創(chuàng)新互聯(lián)已為近1000家的企業(yè)提供了網(wǎng)站建設(shè)、域名、網(wǎng)頁(yè)空間、網(wǎng)站托管、企業(yè)網(wǎng)站設(shè)計(jì)、覃塘網(wǎng)站維護(hù)等服務(wù),公司將堅(jiān)持客戶導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長(zhǎng),共同發(fā)展。
索引器允許類或結(jié)構(gòu)的實(shí)例就像數(shù)組一樣進(jìn)行索引。
二、 索引器使用
索引器經(jīng)常是在主要用于封裝內(nèi)部集合或數(shù)組的類型中實(shí)現(xiàn)的。
C# 并不將索引類型限制為整數(shù)
三、 接口索引器與類索引器的區(qū)別:
接口訪問(wèn)器不使用修飾符。
接口訪問(wèn)器沒(méi)有體。
四、 索引器與屬性的區(qū)別:
索引器與屬性類似。 除下表中顯示的差別外,為屬性訪問(wèn)器定義的所有規(guī)則同樣適用于索引器訪問(wèn)器。
屬性 |
索引器 |
允許像調(diào)用公共數(shù)據(jù)成員一樣調(diào)用方法。 |
允許對(duì)一個(gè)對(duì)象本身使用數(shù)組表示法來(lái)訪問(wèn)該對(duì)象內(nèi)部集合中的元素。 |
可通過(guò)簡(jiǎn)單的名稱進(jìn)行訪問(wèn)。 |
可通過(guò)索引器進(jìn)行訪問(wèn)。 |
可以為靜態(tài)成員或?qū)嵗蓡T。 |
必須為實(shí)例成員。 |
屬性的 get 訪問(wèn)器沒(méi)有參數(shù)。 |
索引器的 get 訪問(wèn)器具有與索引器相同的形參表。 |
屬性的 set 訪問(wèn)器包含隱式 value 參數(shù)。 |
除了值參數(shù)外,索引器的 set 訪問(wèn)器還具有與索引器相同的形參表。 |
支持對(duì)使用短語(yǔ)法。 |
不支持短語(yǔ)法。 |
五、 索引器示例:
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5: using System.Collections.Specialized;
6:
7: namespace CSharp.Indexer
8: {
9: public class Employee
10: {
11: private string _name = "";
12:
13: public string Name
14: {
15: get { return _name; }
16: set { _name = value; }
17: }
18:
19: public Employee(string name)
20: {
21: this._name = name;
22: }
23: }
24:
25: public interface IEmployeeInterface
26: {
27: //int Indexer declaration
28: Employee this[int index]
29: {
30: set;
31: }
32:
33: //string indexer declaration
34: Employee this[string name]
35: {
36: get;
37: set;
38: }
39: }
40:
41: public class EmployeeList : IEmployeeInterface
42: {
43: private ListDictionary empDictionary;
44:
45: public EmployeeList()
46: {
47: empDictionary = new ListDictionary();
48: }
49:
50: // The int indexer.
51: public Employee this[int item]
52: {
53: set
54: {
55: if (value != null && !string.IsNullOrEmpty(value.Name))
56: {
57: empDictionary.Add(value.Name, value);
58: }
59: }
60: }
61:
62: // The string indexer.
63: public Employee this[string name]
64: {
65: get { return (Employee)empDictionary[name]; }
66: set { empDictionary.Add(name, value); }
67: }
68: }
69:
70: class Program
71: {
72: static void Main(string[] args)
73: {
74: EmployeeList empList = new EmployeeList();
75:
76: empList[0] = new Employee("david");
77: empList[1] = new Employee("lisa");
78: empList[2] = new Employee("nana");
79:
80: empList["alice"] = new Employee("alice");
81: empList["sam"] = new Employee("sam");
82:
83: Employee alice = empList["alice"];
84: Console.WriteLine("Alice 's name is {0}", alice.Name);
85: Employee nana = empList["nana"];
86: Console.WriteLine("Nana 's name is {0}", nana.Name);
87:
88: Console.ReadLine();
89: }
90: }
91: }
分享標(biāo)題:C#語(yǔ)言知識(shí)點(diǎn)整理-索引
分享URL:http://fisionsoft.com.cn/article/jejhih.html