我正在尝试List<KeyValuePair<string,int>>通过覆盖索引器来添加查找元素的功能.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public class MyList : List<KeyValuePair<string, int>>
{
public int this[string key]
{
get
{
return base.Single(item => item.Key == key).Value;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
出于某种原因,编译器抛出此错误:
'
System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<string,int>>'不包含'Single' 的定义.
虽然List<T>没有那个方法,但它应该是可见的,因为它是来自System.Linq命名空间的扩展方法(包括在内).显然使用this.Single解决问题,但为什么通过base错误访问?
C#规范第7.6.8节说
当
base.I发生在类或结构中时,I必须表示该类或结构的基类的成员.
这似乎阻止了对扩展方法的访问base.不过它也说
在绑定时,表单的基本访问表达式
base.I和base[E]它们的编写方式完全相同,((B)this).I并且((B)this)[E]在哪里B是构造发生的类或结构的基类.因此,base.I与base[E]对应于 …