问题
如果我的类有这样的定义:
public class TestList : ObservableCollection<TestClass>, IList<ITestInterface>, ICollection<ITestInterface>, IEnumerable<ITestInterface>, IEnumerable
Run Code Online (Sandbox Code Playgroud)
我不能在此类的对象上使用IEnumerable扩展方法(System.Linq命名空间).
注意事项
ObservableCollection的类型与集合接口中的类型不同,但TestClass实现的类型ITestInterfaceforeach覆盖TestList对象中的项目.这样做可以为项目提供类型TestClassusing声明System.Linq它显然与类中的ObservableCollection类型与类定义中的其他类型不同,但为什么呢?该集合仍然可以在一个foreach语句中枚举,这基本上就是那些扩展方法所做的事情(当然还有其他逻辑).
问题
为什么创建一个继承自一个类型的集合并实现另一个类型的集合接口的类会导致扩展方法System.Linq无法在类的对象上使用?
最小,完整和可验证的示例
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace TestApp
{
class Program
{
static void Main(string[] args)
{
var t = new TestList();
t.First(); //Extension method unavailable, compiler error
foreach (var item in t)
{
//item …Run Code Online (Sandbox Code Playgroud)