可以在泛型方法中使用IList,但不能使用List
本文关键字:但不能 List IList 泛型方法 | 更新日期: 2023-09-27 18:05:40
我试图创建一个方法,返回用户想要的任何类型的列表。为了做到这一点,我使用了泛型,我对它不太熟悉,所以这个问题可能很明显。问题是这段代码不起作用,并抛出错误消息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 ?收集。品牌从第三方库返回BrandCollection
类型,所以我不知道这是如何创建的。可能是BrandCollection
可能来自IList(只是猜测它确实如此),因此它可以转换为它,但不能转换为正常的List?
由于T
没有约束,所以只能在编译时转换为object
。对接口类型的强制转换不会被编译器检查,因为理论上可以创建一个实现IList<object>
并继承List<Brand>
的新类。然而,强制转换到List<T>
将会失败,因为我们知道不能创建同时继承List<object>
和List<Brand>
的类。但是,在您的示例中,您通过switch
语句知道类型T
是什么,并希望强制强制类型转换。要做到这一点,首先通过object
强制转换,如下所示:
private List<T> ConvertToList<T>(Category cat)
{
switch (cat)
{
case Category.Brands:
return (List<T>)(object)collection.Brands.ToList<Brand>();
}
}
这里更大的设计问题是,当您拥有T
的已知类型离散列表时,泛型不是最佳选择。当T
可以是任何类型,或者被约束为基类型或接口时,泛型更好。在这里,您最好为switch语句的每个分支编写一个单独的方法:
private List<Brand> ConvertToBrandList()
{
return collection.Brands.ToList<Brand>();
}
如果没有这个,就没有类型安全性。如果有人用ConvertToList<int>(Category.Brands)
调用你的方法怎么办?