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

本文关键字:多级 泛型类型 接口 | 更新日期: 2023-09-27 18:21:37

说我有以下接口

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

我该怎么做?

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

您试图将IOutput中的泛型参数Shopper视为协变参数。在声明接口时,您需要明确声明该泛型参数是协变的:

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

(注意out关键字。)

然后代码编译。

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

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

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

只有当IOutput相对于其泛型参数是协变的时,该转换才有效。