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

C#中的索引举例

2016-04-04 13:54 369 查看

源码:

using System;
class IndexerRecord
{
private string[] data = new string[6];
private string[] keys = {
"Author", "Publisher", "Title",
"Subject", "ISBN", "Comments"
};

//注:程序中用了两种方法来索引:
//一是整数作下标,二是字符串(关键词名)作下标
public string this[int idx]
{
set
{
if (idx >= 0 && idx < data.Length)
data[idx] = value;
}
get
{
if (idx >= 0 && idx < data.Length)
return data[idx];
return null;
}
}
public string this[string key]
{
set
{
int idx = FindKey(key);
this[idx] = value;
}
get
{
return this[FindKey(key)];
}
}
private int FindKey(string key)
{
for (int i = 0; i < keys.Length; i++)
if (keys[i] == key) return i;
return -1;
}
static void Main()
{
IndexerRecord record = new IndexerRecord();
record[0] = "马克-吐温";
record[1] = "Crox出版公司";
record[2] = "汤姆-索亚历险记";
Console.WriteLine(record["Title"]);
Console.WriteLine(record["Author"]);
Console.WriteLine(record["Publisher"]);
}
}

运行效果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: