通用列表中的类型混合

时间:2009-07-23 13:36:54

标签: .net generics

我正在尝试执行以下操作:

List<IRepository<IBusinessObject, ICriteria>> Repositories { get; }

并通过

调用此方法
IRepository<ICustomer, ICustomerCriteria> cr = new CustomerRepository();

List.Add(CustomerRepository);

其中ICustomer和ICustomerCriteria分别来自IBusinessObject和ICriteria。

然而,编译器不喜欢这个。

嗯,我知道我推了一下,但我觉得这会有用吗?谁知道为什么?

由于 邓肯

2 个答案:

答案 0 :(得分:3)

C#不支持泛型的协方差。考虑这个Covariance and Contravariance in C#, Part One

答案 1 :(得分:1)

这是一个generic variance问题:

这将说明问题:

List<string> Strings = ...;
List<object> Objects = Strings; // Should work

Objects.Add(42); // 42 is an object - Should work
// But we would add an integer into a list of strings!!

在.NET FX 4中,C#将支持一种特殊的inout通用参数,以允许正确的行为。