C#索引器示例代码

xiaoxiao2026-05-19  10

/** * 索引器允许类和结构的实例按照与数组相同的方式进行索引,索引器类似与属性,不同之处在于他们的访问器采用参数。被称为有参属性。 * 索引器与属性的比较: * □标示方式:属性以名称来标识,索引器以函数签名来标识。 * □索引器可以被重载。属性则不可以被重载。 * □属性可以为静态的,索引器属于实例成员,不能被声明为static * * 备注: * □所有索引器都使用this关键词来取代方法名。Class或Struct只允许定义一个索引器,而且总是命名为this。 * □索引器允许类或结构的实例按照与数组相同的方式进行索引。索引器类似于属性,不同之处在于它们的访问器采用参数。 * □get 访问器返回值。set 访问器分配值。 * □this 关键字用于定义索引器。 * □value 关键字用于定义由 set 索引器分配的值。 * □索引器不必根据整数值进行索引,由您决定如何定义特定的查找机制。 * □索引器可被重载。 * □索引器可以有多个形参,例如当访问二维数组时。 * □索引器可以使用百数值下标,而数组只能使用整数下标:如下列定义一个String下标的索引器 * □public int this [string name] {...} * □属性和索引器 * ○属性和索引器之间有好些差别: * ○类的每一个属性都必须拥有唯一的名称,而类里定义的每一个索引器都必须拥有唯一的签名(signature)或者参数列表(这样就可以实现索引器重载)。 * ○属性可以是static(静态的)而索引器则必须是实例成员。 */using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Collections;namespace IndexExample{ /// <summary> /// 多参数索引器实例 /// </summary> class Program { static void Main(string[] args) { ScoreIndex si = new ScoreIndex(); si["张三", 1] = 90; si["张三", 2] = 100; si["张三", 3] = 80; si["李四", 1] = 60; si["李四", 2] = 70; si["李四", 3] = 50; Console.WriteLine("张三的课程号为1的成绩为:{0}", si["张三", 1]); Console.WriteLine("张三的所有课程成绩是:"); ArrayList arr; arr = si["张三"]; foreach (IndexClass ic in arr) { Console.WriteLine("课程编号:" + ic.CourseId + "\t分数:" + ic.Score); } Console.Read(); } } class IndexClass { private string _name; private int _courseId; private int _score; public IndexClass(string _name, int _courseId, int _score) { this._name = _name; this._courseId = _courseId; this._score = _score; } public string Name { get { return this._name; } set { this._name = value; } } public int CourseId { get { return this._courseId; } set { this._courseId = value; } } public int Score { get { return this._score; } set { this._score = value; } } } class ScoreIndex { private ArrayList arr; public ScoreIndex() { arr = new ArrayList(); } public int this[string _name, int _courseId] { get { foreach (IndexClass ic in arr) { if (ic.Name == _name && ic.CourseId == _courseId) { return ic.Score; } } return -1; } set { arr.Add(new IndexClass(_name, _courseId, value)); } } public ArrayList this[string _name] { get { ArrayList tmp = new ArrayList(); foreach (IndexClass ic in arr) { if (ic.Name == _name) tmp.Add(ic); } return tmp; } } }} 相关资源:几个有关C#索引器的例子(源代码)几个有关C#索引器的例子(源代码)
转载请注明原文地址: https://www.6miu.com/read-5049045.html

最新回复(0)