深度优先

这个家伙好懒,除了文章什么都没留下

0%

【CSharp】索引器

https://www.cnblogs.com/tynam/p/13611709.html

概念

索引器(Indexer) 允许类中的对象可以像数组那样方便、直观的被引用。当为类定义一个索引器时,该类的行为就会像一个 虚拟数组(virtual array) 一样。
索引器可以有参数列表,且只能作用在实例对象上,而不能在类上直接作用。
可以使用数组访问运算符([ ])来访问该类的实例。
索引器的行为的声明在某种程度上类似于属性(property)。属性可使用 get 和 set 访问器来定义索引器。但是属性返回或设置的是一个特定的数据成员,而索引器返回或设置对象实例的一个特定值。

定义一个一维数组的索引器:

1
2
3
4
5
6
7
8
9
10
11
12
13
element-type this[int index]
{
// get 访问器
get
{
// 返回 index 指定的值
}
// set 访问器
set
{
// 设置 index 指定的值
}
}

提示:索引器必须以this关键字定义,this 是类实例化之后的对象

实例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using System;

namespace C_Pro
{
public class Student
{
private string name;
private string grade;
public string Name
{
get {return name; }
set {name = value; }
}
public string Grade
{
get {return grade; }
set {grade = value; }
}
// 定义索引器
public string this[int index]
{
get
{
if (index == 0) return name;
else if (index == 1) return grade;
else return null;
}
set
{
if (index == 0) name = value;
else if (index == 1) grade = value;
}
}
static void Main(string[] args)
{
Student s = new Student();
s[0] = "Jeson";
s[1] = "First-year";
Console.WriteLine(s.Name);
Console.WriteLine(s.Grade);
Console.ReadKey();
}
}
}

输出:

1
2
3
Jeson

First-year

重载索引器

索引器(Indexer)可被重载。索引器声明的时候也可带有多个参数,且每个参数可以是不同的类型。没有必要让索引器必须是整型的。CSharp 允许索引器可以是其他类型,例如,字符串类型。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using System;

namespace C_Pro
{
public class IndexedNames
{
private string[] namelist = {"a", "b", "c", "d"};
// 输入namelist的index返回对应的值
public string this[int index]
{
get
{
return namelist[index];
}
set
{
namelist[index] = value;
}
}
// 输入namelist的值,返回对应的索引
public int this[string name]
{
get
{
for (int i=0; i<namelist.Length; i++)
{
if (namelist[i] == name) return i;
}
return -1;
}
}

static void Main(string[] args)
{
IndexedNames name = new IndexedNames();
Console.WriteLine(name[1]);
Console.WriteLine(name["a"]);
}
}
}

运行后结果:

1
2
b
0

索引器与数组的区别:

  • 索引器的索引值(Index)类型不限定为整数,用来访问数组的索引值(Index)一定为整数,而索引器的索引值类型可以定义为其他类型。
  • 索引器允许重载, 一个类不限定为只能定义一个索引器,只要索引器的函数签名不同,就可以定义多个索引器,可以重载它的功能。
  • 索引器不是一个变量,索引器没有直接定义数据存储的地方,而数组有。索引器具有Get和Set访问器。

索引器与属性的区别:

  • 索引器以函数签名方式 this 来标识,而属性采用名称来标识,名称可以任意。
  • 索引器可以重载,而属性不能重载。
  • 索引器不能用static 来进行声明,而属性可以。索引器永远属于实例成员,因此不能声明为static。