我想创建一个方法,它返回用户想要的任何类型的列表。要做到这一点,我使用的泛型,我不太熟悉,所以这个问题可能很明显。问题是,这个代码不工作,并引发错误消息Cannot convert type Systems.Collections.Generic.List<CatalogueLibrary.Categories.Brand> to Systems.Collection.Generic.List<T>
可以使用IList但不是列表中的泛型方法
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(只是猜测它确实),所以它可以转换为它,但不是正常的列表?
你应该把类型约束放在那里!你不能只是围绕着铸造东西。 – antonijn 2013-03-24 20:17:17
你确定你的第二个例子不是'return(IList)collection.Brands.ToList ();'? –
Matthew
2013-03-24 20:18:13
我打算在这个工作后看看。我对泛型有点新,所以我认为在后面的情况下它会破坏别的东西:D约束条件是'T:品牌'(和其他类别)吗? – XSL 2013-03-24 20:18:30