0

据此_

“索引器不必由整数值索引;如何定义特定的查找机制取决于您。”

但是,下面的代码因异常而中断

未处理的异常:System.IndexOutOfRangeException:索引超出了数组的范围。

using System; 
using System.Linq; 

namespace ConsoleApplication
{
    class Program
    {
        private static string fruits;

        static void Main(string[] args)
        {
            fruits = "Apple,Banana,Cantaloupe";
            Console.WriteLine(fruits['B']);
        }

        public string this[char c] // indexer 
        { 
            get
            {    
              var x=  fruits.Split(',');    
                return x.Select(f => f.StartsWith(c.ToString())).SingleOrDefault().ToString();    
            }    
        }
    }
}

上面的代码不应该能够使用 char 索引而不是 int 索引吗?

4

3 回答 3

6

您的链接是指您自己定义的索引器:

public T this[int i]

但是你没有使用你定义的索引器,你使用的是string类的索引器,它被定义为接受一个int参数。

其他类其他类型索引 - 例如,由以下Dictionary<TKey,TValue>内容索引TKey

var dic = new Dictionary<string,int>();
dic["hello"] = 1;
于 2013-07-11T20:52:17.283 回答
3

您没有在示例中使用索引器,为该类创建了一个索引器,Program但您需要在该类上使用一个索引器String

即使索引器期望一个 int 是一个字符,它仍然可以工作的原因是可以转换为 aint所以在你的代码中你真的在做

Console.WriteLine(fruits[((int)'B')]);
于 2013-07-11T20:53:44.383 回答
3

Main 是一个静态方法,您正在尝试访问该类的非静态属性Program。您定义的索引器甚至没有远程连接到String该类。为了引用您的索引器,您需要:

Program program = new Program();
program.fruits = "Bananas";
Console.WriteLine(program['B']);

但是上面的代码很糟糕,你永远不应该使用这样的怪物。相反,声明另一个类并在那里实现索引器;

于 2013-07-11T20:54:59.223 回答