C# 子类化列表<;T>;不保留列表功能
我创建了一个泛型列表的子类,以便实现一个新接口C# 子类化列表<;T>;不保留列表功能,c#,inheritance,C#,Inheritance,我创建了一个泛型列表的子类,以便实现一个新接口 public class CustomersCollection : List<Customer>, IEnumerable<SqlDataRecord> { ... } 为什么CustomerCollection不继承列表的IQueryable、IEnumerable接口实现 官方错误是: “CustomerCollection”不包含 “Where”和no的定义 扩展方法“Where”接受 类型的第一个参数 找不到“C
public class CustomersCollection : List<Customer>, IEnumerable<SqlDataRecord>
{
...
}
为什么CustomerCollection不继承列表的IQueryable、IEnumerable接口实现
官方错误是:
“CustomerCollection”不包含
“Where”和no的定义
扩展方法“Where”接受
类型的第一个参数
找不到“CustomerCollection”
(您是否缺少using指令或
组件参考?)
事实证明,IEnumerable的自定义实现导致应用于IEnumerable的所有扩展方法失败。这是怎么回事?从
列表继承的类可以使用扩展方法。也许您需要使用System.Linq添加代码>到您的代码文件?还要检查您是否有对System.Core.dll
的引用
编辑
由于同一类继承/实现了List
和IEnumerable
,因此在使用扩展方法时需要提供类型。例如:
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);
}
CustomerCollection客户=新CustomerCollection();
添加(新客户(){Name=“Adam”});
添加(新客户(){Name=“Bonita”});
foreach(customers.Where(c=>c.Name==“Adam”)中的客户c)
{
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();
}
}
class客户{公共字符串名称{get;set;}
类Foo{}
类CustomerCollection:列表,IEnumerable
{
私有IList foos=新列表();
公共新IEnumerator GetEnumerator()
{
返回foos.GetEnumerator();
}
}
其中
不是继承的,但它需要实现IEnumerable
,这是通过继承提供的。同意CustomersCollection
具有LINQ中需要使用的所有内容。感谢您的回复,但这不是解决方案。此代码正在使用列表。一旦我将其更改为CustomerCollection,代码就无法编译。没有缺少引用或命名空间导入。这就是我感到困惑的原因。您确定从实现了IEnumerable
的类继承而重写它来实现IEnumerable
有什么意义吗?简单地添加一个返回IEnumerable
的方法以避免使事情复杂化不是更好吗?
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();
}
}