c# - 子类化 List<T> 不保留列表功能

标签 c# inheritance

我已经创建了一个泛型列表的子类,这样我就可以实现一个新接口(interface)

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接口(interface)实现?

官方错误是:

'CustomersCollection' does not contain a definition for 'Where' and no extension method 'Where' accepting a first argument of type 'CustomersCollection' could be found (are you missing a using directive or an assembly reference?)


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

最佳答案

扩展方法可用于继承自 List<T> 的类.也许您需要添加 using System.Linq;到你的代码文件?还要检查您是否有对 System.Core.dll 的引用.

编辑

既然你有List<U>IEnumerable<T>由同一个类继承/实现,您需要在使用扩展方法时提供类型。示例:

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();
    }
}

关于c# - 子类化 List<T> 不保留列表功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3110893/

相关文章:

c# - 如何使用 jQuery 禁用按钮,但在单击按钮后运行服务器代码?

c# - 标记从我的应用程序访问网站的用户

C# 隐式更新传递给没有返回类型且没有 out 或 ref 用法的方法的参数

c# - 如何找到引用错误版本程序集的内容并修复它?

c# - 在 C# 中的 DataGridView 中创建列

c++11继承模板构造函数

java - 从子类引用父类(super class)时,父类(super class)的字段值显示为零

c# - 如何找到基类的直接后代类型?

Python类-属性继承

java - 为什么调用父类方法?