gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:24:47 29 4
gpt4 key购买 nike

我已经创建了一个泛型列表的子类,这样我就可以实现一个新接口(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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com