C#中一个索引器调用另一个索引器的问题
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespa...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IndexerTest
{
class Program
{
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; //调用参数为int的索引器
}
get
{
return this[ FindKey(key) ]; //调用参数为Int的索引器
}
}
private int FindKey(string key)
{
for (int i = 0; i < keys.Length; i++)
if (keys[i] == key) return i;
return -1;
}
static void Main(string[] args)
{
Program indexertest = new Program();
indexertest[0] = "马克-吐温";
indexertest[1] = "Crox 出版公司";
indexertest[2] = "汤姆索亚历险记";
Console.WriteLine(indexertest["Title"]);
Console.WriteLine(indexertest["Author"]);
Console.WriteLine(indexertest["Publisher"]);
}
}
}
这是一段教科书上的代码。但是在VS2008中运行出来的结果却没有调用上面的Int型的索引器。求大侠指教。 展开
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IndexerTest
{
class Program
{
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; //调用参数为int的索引器
}
get
{
return this[ FindKey(key) ]; //调用参数为Int的索引器
}
}
private int FindKey(string key)
{
for (int i = 0; i < keys.Length; i++)
if (keys[i] == key) return i;
return -1;
}
static void Main(string[] args)
{
Program indexertest = new Program();
indexertest[0] = "马克-吐温";
indexertest[1] = "Crox 出版公司";
indexertest[2] = "汤姆索亚历险记";
Console.WriteLine(indexertest["Title"]);
Console.WriteLine(indexertest["Author"]);
Console.WriteLine(indexertest["Publisher"]);
}
}
}
这是一段教科书上的代码。但是在VS2008中运行出来的结果却没有调用上面的Int型的索引器。求大侠指教。 展开
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询