根据这个
"索引器不必用整数值索引;由你决定如何定义特定的查找机制."
但是,下面的代码打破了一个例外
未处理的异常: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();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码不应该使用char索引而不是int索引吗?
您的链接指的是您自己定义的索引器:
public T this[int i]
Run Code Online (Sandbox Code Playgroud)
但是您没有使用已定义的索引器,而是使用类的索引器,该索引器string被定义为接受int参数.
其他类是由其他类型的索引-例如,Dictionary<TKey,TValue>通过任何索引TKey是:
var dic = new Dictionary<string,int>();
dic["hello"] = 1;
Run Code Online (Sandbox Code Playgroud)