什么是C#中的索引器?
索引器允许对对象(例如数组)进行索引。
让我们看看语法-
element-type this[int index] {
//获取访问器。
get {
//返回由索引指定的值
}
//设置的访问器。
set {
//设置索引指定的值
}
}以下是显示如何在C#中实现索引器的示例-
示例
using System;
namespace Demo {
class Program {
private string[] namelist = new string[size];
static public int size = 10;
public Program() {
for (int i = 0; i < size; i++)
namelist[i] = "N. A.";
}
public string this[int index] {
get {
string tmp;
if( index >= 0 && index <= size-1 ) {
tmp = namelist[index];
} else {
tmp = "";
}
return ( tmp );
}
set {
if( index >= 0 && index <= size-1 ) {
namelist[index] = value;
}
}
}
static void Main(string[] args) {
Program names = new Program();
names[0] = "Tom";
names[1] = "Jacob";
names[2] = "Jack";
names[3] = "Amy";
names[4] = "Katy";
names[5] = "Taylor";
names[6] = "Brad";
names[7] = "Scarlett";
names[8] = "James";
for ( int i = 0; i < Program.size; i++ ) {
Console.WriteLine(names[i]);
}
Console.ReadKey();
}
}
}输出结果
Tom Jacob Jack Amy Katy Taylor Brad Scarlett James N. A.
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短