【发布时间】:2013-03-24 20:13:32
【问题描述】:
我正在尝试创建一个方法,该方法返回用户想要的任何类型的列表。为此,我使用了泛型,我不太熟悉,所以这个问题可能很明显。问题是这段代码不起作用并抛出错误消息Cannot convert type Systems.Collections.Generic.List<CatalogueLibrary.Categories.Brand> to Systems.Collection.Generic.List<T>
private List<T> ConvertToList<T>(Category cat)
{
switch (cat)
{
case Category.Brands:
return (List<T>)collection.Brands.ToList<Brand>();
}
...
}
但如果我改用IList,则没有错误。
private IList<T> ConvertToList<T>(Category cat)
{
switch (cat)
{
case Category.Brands:
return (IList<T>)collection.Brands.ToList<Brand>();
}
...
}
为什么在这种情况下我可以使用 IList 而不是 List? collection.Brands 从第三方库返回 BrandCollection 类型,所以我不知道它是如何创建的。难道BrandCollection 可能源自 IList(只是猜测它确实如此),因此它可以转换为它,但不能转换为普通的 List?
【问题讨论】:
-
你应该把类型限制在那里,伙计!你不能无所事事地到处铸造东西。
-
你确定你的第二个例子不是
return (IList<T>)collection.Brands.ToList<T>();? -
我打算在这工作后进行调查。我对泛型有点陌生,所以我想我会把它留到以后,以防它破坏其他东西:D 约束是
where T : Brand(和其他类别)吗? -
我觉得你这里的通用用法不正确。
-
@Matthew - 我尝试使用 ToList
但我得到了 Instance argument: cannot convert from '..BrandCollection' to 'System.Collections.Generic.IEnumerable<T>'
标签: c# list generics interface ilist