【问题标题】:Subclassing List<T> doesnt retain lists functionality子类化 List<T> 不保留列表功能
【发布时间】:2010-06-24 23:09:47
【问题描述】:

我创建了一个通用列表的子类,以便我可以实现一个新接口

public class CustomersCollection : List<Customer>, IEnumerable<SqlDataRecord>
{
...
}

当我将字段定义更改为新类时(请参阅下面的新旧行示例),我会在原始列表中应该存在的内容上遇到各种编译错误。

public CustomersCollection Customers { get; set; } 
public void Sample()
{
    Console.WriteLine(Customers.Where(x=>x.condition).First().ToString());
}

为什么CustomersCollection不继承List的IQueryable、IEnumerable接口实现?

官方的错误是:

'CustomersCollection' 不包含 'Where' 和 no 的定义 扩展方法“Where”接受 类型的第一个参数 可以找到“CustomersCollection” (您是否缺少 using 指令或 程序集参考?)


事实证明,IEnumerable 的自定义实现会导致所有适用于 IEnumerable 的扩展方法失败。这是怎么回事?

【问题讨论】:

  • 您确定从实现IEnumerable&lt;Customer&gt; 的类继承但重写它以实现IEnumerable&lt;SqlDataRecord&gt; 是否有意义?简单地添加一个返回IEnumerable&lt;SqlDataRecord&gt;的方法以避免复杂化不是更好吗?

标签: c# inheritance


【解决方案1】:

扩展方法可用于从List&lt;T&gt; 继承的类。也许您需要将using System.Linq; 添加到您的代码文件中?还要检查您是否引用了System.Core.dll

编辑

由于List&lt;U&gt;IEnumerable&lt;T&gt; 被同一个类继承/实现,因此在使用扩展方法时需要提供类型。示例:

CustomerCollection customers = new CustomerCollection();
customers.Add(new Customer() { Name = "Adam" });
customers.Add(new Customer() { Name = "Bonita" });
foreach (Customer c in customers.Where<Customer>(c => c.Name == "Adam"))
{
    Console.WriteLine(c.Name);
}

...基于

class Customer { public string Name { get; set; } }    

class Foo { }

class CustomerCollection : List<Customer>, IEnumerable<Foo>
{
    private IList<Foo> foos = new List<Foo>();

    public new IEnumerator<Foo> GetEnumerator()
    {
        return foos.GetEnumerator();
    }
}

【讨论】:

  • Where 不是继承的,但需要实现IEnumerable,这里是通过继承提供的。同意CustomersCollection 拥有所有需要在 LINQ 中使用的东西。
  • 感谢您的回复,但这不是解决方案。此代码与 List 一起使用。一旦我将其更改为 CustomerCollection,代码就无法编译。没有缺少引用或命名空间导入。这就是为什么我很困惑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-12
  • 2011-09-09
  • 1970-01-01
  • 2013-08-03
  • 2011-12-26
  • 1970-01-01
相关资源
最近更新 更多