您的位置:首页 > 编程语言 > C#

C#索引器学习笔记

2017-04-26 19:18 253 查看
首先看看索引器的本质:索引器是一个存在于类或者结构中的形式极度相似于属性(对字段的封装)的特殊方法。索引器是一个实例化的方法(不能定义为静态static的,它属于对象),拥有get与set访问器。其中get访问器具有和索引器相同的形参表,set访问器具有和索引器相同的形参表+value。说白了,索引器就是属性的加强版本——它可以将多个字段(当然这个字段可以是普通变量型的,也可以是数组/顺序表等)同时进行封装,而属性只能对一个字段进行封装!

再看看索引器和数组、属性的一些比较:

(1)和数组比较:

①数组的下标必须是int型;而索引器的下标无限制(int/string等)。

②索引器是类/结构中的一个成员,所以允许成员重载(也就是同名不同参的方法。C#的运算符重载是在某些运算符原有的功能上进行扩展);数组当然不能重载!

③数组是一种自定义引用类型变量,而索引器是一种特殊方法。

(2)和属性的比较:

①属性封装单个字段,而索引器可以封装多个字段;

②属性以名称来标识,可以静态(属于类),也可以非静态(属于对象)。而索引器以函数形式标识,必须是非静态的(属于对象);

③属性不能重载(参数都没有!),索引器可以重载;

一些示例代码:

public class TestClass
{
//索引器将封装这3个字段
private float Chinese = 95;
private float Math = 100;
private float English = 93;
public float this[int index]
{
set
{
switch(index)
{
case 0: Chinese = value; break;
case 1: Math = value; break;
case 2: English = value; break;
default: Console.WriteLine("超出索引!"); break;
}
}
get
{
switch(index)
{
case 0: return this.Chinese;
case 1: return this.Math;
case 2: return this.English;
default: throw new ArgumentOutOfRangeException();
}
}
}
}
class SomePlace
{
static void Main(string[] args)
{
TestClass tc = new TestClass();
tc[0] = 99;
tc[1] = 100;
tc[2] = 95;
tc[3] = 99;
Console.WriteLine("语文:{0},数学:{1},英语:{2}", tc[0], tc[1], tc[2]);
Console.ReadKey();
}
}


class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
get
{
return arr[i];
}
set
{
arr[i] = value;
}
}
}

// This class shows how client code uses the indexer
class Program
{
static void Main(string[] args)
{
SampleCollection<string> stringCollection = new SampleCollection<string>();
stringCollection[0] = "Hello, World";
System.Console.WriteLine(stringCollection[0]);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c# 索引器