一周学会C#(索引一)

一周学会 C# (索引一)

C# 才鸟( QQ:249178521 )

1.[]

· ** 索引提供 ** ** [ ] ** ** 类的语法 ** ** **

w ** 总是一个实例成员,可以是虚拟的 ** **_ _ ** ** **

w ** 没有 ** **_ ref/out _ ** **_ 参数 _ ** ** **

** struct StringSection **

** { **

** ... **

** public char this [int at] **

** { **

** ... **

** } **

** ... **

** } **

** StringSection cord("csharp", 2, 6); **

** ... **

** char first = cord[0]; // 'h' **

** ... **

** Console.WriteLine(cord); // harp **

索引的声明包括:可选的访问修饰符(例子中是 public ),返回值的类型( char ),关键字 this (不能省略),和函数参数类似的参数(不过是方括号,而不是函数的圆括号),然后是索引体。你不能使用静态索引,所以你不能在索引的声明中使用 static 关键字。

索引可以被声明为虚拟的,因此它可以在它的派生类中被重载。

索引的参数不能使用 ref/out 型参数。例如:

struct StringSection

{

public char this [ref int at]// 错误

...

}

2. 读和写

· ** 索引只能包含下列语句 ** ** **

w **_ get _ ** ** { } ** ** 用来读 ** ** **

w **_ set _ ** ** { } ** ** 用来写 ** ** **

** struct StringSection **

** { **

** ... **

** public char this [int at]
{ **

** get { return ...; } **

** set { ... = value; } **

** } **

** ... **

** } **

** cord[3] = 'e'; **

** if (cord[3] == 'e') ... **

索引的声明和属性一样:只能含有 set/get 语句。

当使用一个索引表达式进行读操作时,索引的 get 语句自动运行,例如在上面的例子中,表达式:

cord[3] == 'e'

系统会自动调用 索引的 get 语句( 3 传递给索引的整型参数),返回一个 char 型值,这个 char 型值然后和 'e' 进行比较。

当使用一个索引表达式进行写操作时,索引的 set 语句自动运行,例如在上面的例子中,表达式:

cord[3] = 'e'

系统会自动调用 索引的 set 语句( 3 传递给索引的整型参数), set 语句可以取得表达式右边的值,它是通过 value 这个“关键字”来获得的。

3. 只读或只写

· ** 只有 ** **_ get _ ** ** ** ** 语句的索引是 ** ** **

w ** 只读索引 ** ** **

· ** 只有 ** **_ set _ ** ** ** ** 语句的索引是 ** ** **

w ** 只写索引 ** ** **

** struct StringSection **

** { **

** ... **

** public char this [int at] **

** { **

** get { return ... } **

** } **

** ... **

** } **

** StringSection cord("csharp", 1, 6); **

** ... **

** if (cord[4] == 'k') { **

** cord[4] = 'k'; // ** ** 错误 **

** } **


Published At
Categories with Web编程
Tagged with
comments powered by Disqus