using System;
class IndexerRecord
{
private string[] data = new string[6];
//定义了一个字符串数组data
private string[] keys = {"Author","Publish","Title","subject","isbn","comments"};
//定义一个字符串型数组keys并初始化
/// <summary>
/// this指的是什么?
/// </summary>
/// <param name="idx"></param>
/// <returns></returns>
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];
}
else
{
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;
}
/// <summary>
/// Main
/// </summary>
static void Main()
{
IndexerRecord record = new IndexerRecord();
//这里不是定义了数组,是新建了一个IndexRecord的对象
record[0] = "马克吐温"; //数组元素0 赋值
record[1] = "Crox出版公司"; //数组元素1 赋值
record[2] = "汤姆-索亚历险记"; //数组元素2 赋值
Console.WriteLine(record["Title"]);
Console.WriteLine(record["Author"]);
Console.WriteLine(record["Publisher"]);
record.data.SetValue("intro", 5);//设定第6个的值为intro
/*也有GetValue方法,只不过是用来取值的*/
Console.WriteLine(record[6]);//输出第6个的值
}
}
浙公网安备 33010602011771号