前言:
在博文《接口包含内容概述1——接口相关概述及接口中属性的实现》和《接口包含内容概述2——委托与事件之惑》中,对接口中的属性以及事件的实现做了基本描述, 今天就接口中可以包含的另一部分内容、也是我不太熟悉的内容——索引器的概括以及在接口中的实现做一说明。
索引器的概述:
数组,对象可以按照索引编号对对象中的集合进行存(set)和取(get)操作。这是雷同于数组的方面。然而在类中声明、定义方式,却更相似于属性——同样采用get 和 set访问器(accessor)。 在此只是简要说明,下面用一代码具体实现之,同时也有了索引器的初步理解:
1
//
Description: 通过建立类Student,以及引用它的类Team,表现索引的使用方法
2
3
//
CopyRight:
4
5
//
Notes: 为简便,将类Student和类Team,以及验证代码放于一起。同时没有对索引中的索引编号越界做判断
6
namespace
IndexerAtClassDemo
7
{
8
//
对类Student 的定义,以便于类Team 中应用
9
public
class
Student
10
{
11
private
string
name;
12
public
string
Name
13
{
14
get
{
return
name; }
15
set
{ name
=
value; }
16
}
17
}
18
19
//
类Team的定义
20
public
class
Team
21
{
22
//
先声明一Student 数组
23
private
Student[] student
=
new
Student[
10
];
24
25
//
通过索引编号来引用
26
public
Student
this
[
int
i]
27
{
28
get
{
return
student[i]; }
29
set
{ student[i]
=
value; }
30
}
31
32
//
通过关键字来引用
33
public
Student
this
[
string
n]
34
{
35
get
36
{
37
foreach
(Student s
in
student)
38
{
39
if
(s.Name
==
n)
40
return
s;
41
}
42
return
null
;
43
}
44
}
45
46
}
47
public
class
Program
48
{
49
static
void
Main(
string
[] args)
50
{
51
//
声明两个Student对象
52
Student s1
=
new
Student();
53
s1.Name
=
"
Yangmingming
"
;
54
Student s2
=
new
Student();
55
s2.Name
=
"
Youngman
"
;
56
57
//
声明Team对象
58
Team team
=
new
Team();
59
team[
0
]
=
s1;
60
team[
1
]
=
s2;
61
62
//
用索引号和关键字作为条件的,对象索引引用
63
Console.WriteLine(
"
The name of s1 and s2 is {0},{1}
"
,team[
0
].Name ,team [
1
].Name);
64
Console.WriteLine(
"
The name of s1 and s2 is {0},{1}
"
,team [
"
Yangmingming
"
].Name,team [
"
Youngman
"
].Name );
65
66
}
67
}
68
}
69
两条输出语句,实现了相同的输出结果,为:
索引,同数组,和属性,有点难以区分。他们的相同点区别大至如下:
1. 索引器,和属性一样,内部实现了get 和set 访问器;
2.在功能上,索引器对于对象而言,实现了数组的功效,同时索引器比数组范围更大:在实现了索引编号访问同时,还实现了关键字索引引用的效果;
3.所有索引器都使用 this 关键字来定义 ;
4.索引器不可以像属性一样,定义为 Static 类型;等等;
索引器在接口中的实现:
索引器在接口中的实现方法。由前对接口中属性的实现方法而自然而然联想,我们有理由相信索引器在接口中应该实现为与属性相似的方法,事实的确如此,见如下代码:
1 //
Description: 通过建立接口IShowInt,以及引用它的类CShowInt,表现索引的接口实现方法
2
3
//
CopyRight:
4
5
//
Notes: 为简便,将接口IShowInt和类CShowInt,以及验证代码放于一起。
6
namespace
IndexAtInterfaceDemo
7
{
8
//
在接口上的索引器定义(indexer)
9
public
interface
IShowInt
10
{
11
12
int
this
[
int
index]
13
{
14
get
;
15
set
;
16
}
17
}
18
19
//
在实现接口的类上,定义索引器(indexer)
20
public
class
CShowInt
21
{
22
private
int
[] arr
=
new
int
[
100
];
23
24
public
int
this
[
int
index]
25
{
26
get
27
{
28
//
确定集合 边界 问题
29
if
(index
>=
0
&&
index
<=
99
)
30
{
31
return
arr[index];
32
}
33
return
0
;
34
}
35
set
36
{
37
if
(index
>=
0
&&
index
<=
99
)
38
arr[index]
=
value;
39
}
40
}
41
}
42
public
class
Program
43
{
44
static
void
Main(
string
[] args)
45
{
46
CShowInt cShowInt
=
new
CShowInt();
47
48
//
对对象使用其中索引器
49
cShowInt[
0
]
=
1
;
50
cShowInt[
1
]
=
2
;
51
52
Console.WriteLine(
"
The int of the Class CShowInt by index is {0},{1}
"
,cShowInt [
0
],cShowInt [
1
]);
53
54
}
55
}
56
}
其实现结果,如下图示:
即实现了接口中索引器的实现。
综述,经过这三篇关于接口中包含内容的讨论,进一步加深了对接口的理解,同时也 进一步学习委托与事件、索引器等。