【发布时间】:2015-03-09 02:58:06
【问题描述】:
我正在尝试通过覆盖索引器来添加在 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;
}
}
}
}
由于某种原因,编译器抛出此错误:
“
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]对应于this.I和this[E],除了this被视为基类的实例。
如果base.I 和((B)this).I 一样,那么这里似乎应该允许扩展方法。
谁能解释这两个陈述中明显的矛盾?
【问题讨论】:
-
你为什么不用字典?
-
您的属性必须具有
int类型,不是吗? -
使用
this而不是base。该属性是Key而不是Name。KeyValuePair没有Value的设置器。该属性应返回类型int。 -
^这是正确的答案,但是为什么你必须使用这个而不是base?
标签: c# linq inheritance extension-methods