【发布时间】:2023-03-25 20:44:01
【问题描述】:
我想要ICollection<T2> 的扩展方法,女巫返回给我IReadOnlyCollection<T1>。为了不在代码中重复自己,我需要所有这些。我有以下代码:
public static IReadOnlyCollection<T1> All<T1, T2>(this ICollection<T2> storage) where T1 : T2
{
if (storage.Count > 0)
{
return new List<T1>(storage);
}
else
{
return new List<T1>();
}
}
但不幸的是它没有编译。 所以让我们看一下上面的一个更简单的例子:
public interface IDatabase {}
public class Database : IDatabase, IDisposable {}
public static IReadOnlyCollection<T1> All<T1, T2>(this ICollection<T2> storage) where T2 : T1 where T1 : new()
{
// compiles
List<Database> derivedList = new List<PublishedDatabase>();
List<IDatabase> baseList = new List<IPublishedDatabase>(derivedList);
// doesn't compile
// with casting it works
List<T2> derivedListT = new List<T2>();
List<T1> baseList1T = new List<T1>(derivedListT/* as IEnumerable<T1>*/);
//...
}
我可以通过泛型使用嵌套类列表创建基类列表而不进行强制转换吗?
【问题讨论】:
-
你为什么不想投?
-
因为我们自己的代码分析器禁止这样做
标签: c# .net generics collections