接口中的C#多级泛型类型

时间:2014-09-12 17:23:38

标签: c# generics

说我有以下接口

using System;

public interface IInput
{

}

public interface IOutput<Shipper> where Shipper : IShipper
{

}

public interface IShipper
{

}


public interface IProvider<TInput, TOutput>
    where TInput : IInput
    where TOutput : IOutput<IShipper>
{

}

我可以创建以下类:

public class Input : IInput
{

}

public class Shipper : IShipper
{

}

public class Output : IOutput<Shipper>
{

}

我尝试了多种方法来创建一个实现IProvider的类而没有运气?

例如:

public class Provider : IProvider<Input, Output>
{

}
Error: The type 'Output' cannot be used as type parameter 'TOutput' in the generic type or method 'IProvider<TInput,TOutput>'. There is no implicit reference conversion from 'Output' to 'IOutput<IShipper>'

public class Provider : IProvider<Input, Output<IShipper>>
{

}
Error: The non-generic type 'Output' cannot be used with type arguments

我该怎么做?

1 个答案:

答案 0 :(得分:4)

您正试图在Shopper中处理通用参数IOutput,就像它的协变一样。在声明接口时,您需要明确声明该泛型参数是协变的:

public interface IOutput<out Shipper> where Shipper : IShipper
{

}

(请注意out关键字。)

然后代码编译。

请注意,进行此更改后,您将无法再使用泛型类型参数Shipper作为该接口的任何成员的参数;如果将它用于这样的庄园,那么界面在概念上是不变的。

您可以实际简化代码,以消除与此问题无关的一些问题。这一切都归结为能够做到以下几点:

IOutput<Shipper> output = new Output();
IOutput<IShpper> = output;

只有当IOutput与其通用参数协变时,该转换才有效。