首页 > 解决方案 > .NET Core Cast 与实现接口的类型的泛型类型参数接口

问题描述

在 .NET Core C# 中,我正在尝试这样的事情:

(IInterface<IParameter>)instance

实例在哪里new Implementation<Parameter>()

Implementation : IInterface&Parameter : IParameter

问题在于泛型参数的转换。当我提供Parameter而不是IParameter它工作但在编译时没有办法知道IParameter将使用哪种类型的实现。所有这些对象都将通过反射创建。

那么这个演员有什么办法吗?或者其他一些实现这一点的方法,比如不提供泛型类型参数,就像你可以使用typeof.

编辑感谢 Ziriax

一个完整的工作示例:

interface IInterface
{
    void Run(TInput input);
}

abstract class AbstractClass<TInput> : IInterface
    where TInput : IParameter
{
    public abstract void Execute(TInput input);

    public void Run(IParameter input)
    {
        Execute((TInput)input);
    }
}

interface IParameter {}

class Implementation : AbstractClass<Parameter>
{
    public void Run(Parameter input)
    {
    }
}

class Parameter : IParameter {}

class Program
{
    static void Main()
    {
        object instance = new Implementation();
        var castInstance = (IInterface) instance;
        castInstance.Run(new Parameter());
    }
}

标签: c#.netgenericsreflectioninterface

解决方案


正如你现在所拥有的,这是行不通的。你的Implementation类 implements IInterface<Parameter>,所以它的Run方法只接受具体Parameter类型的参数,而IInterface<IParameter>要求它的Run方法接受任何类型的实例 implements IParameter

如果允许您尝试执行的演员类型,我可以定义一个不同的类来实现IParameter,例如:

public class DifferentParameter : IParameter { ... }

然后做:

castInstance.Run(new DifferentParameter());

但是你ImplementationRun方法不行DifferentParameter

因此,.NET 会阻止您执行转换本身。

在某些情况下允许这种类型的转换 - 如果您的接口被定义为:

interface IInterface<out TOutput>
    where TOutput : IResult
{
    TOutput Run();
}

通过使泛​​型参数out,它使接口协变。这限制了类型参数的使用作为方法调用的结果,但是对于协变接口,像你这样的转换允许的。

您可以在.NET 文档中找到大量关于协变和逆变的文档。


推荐阅读