.NET Core Cast与具有实现接口的类型的通用类型参数的接口

时间:2018-10-17 18:59:40

标签: c# .net generics reflection interface

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

(IInterface<IParameter>)instance

实例为new Implementation<Parameter>()

还有Implementation : IInterfaceParameter : 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());
    }
}

2 个答案:

答案 0 :(得分:1)

现在,您将无法使用它。您的Implementation类实现了IInterface<Parameter>,因此其Run方法仅接受具体Parameter类型的参数,而IInterface<IParameter>则要求其{{1} }方法接受实现Run any 类型的实例。

如果允许您尝试执行的强制类型转换,则可以定义一个实现IParameter的其他类,例如:

IParameter

然后执行:

public class DifferentParameter : IParameter { ... }

但是您的castInstance.Run(new DifferentParameter()); 的{​​{1}}方法不能采用Implementation

.NET因此使您无法执行强制转换。

在某些情况下,允许这种类型的转换-如果将您的界面定义为:

Run

通过使用通用参数DifferentParameter,可以使接口协变。这限制了类型参数作为方法调用的结果的使用,但是对于协变接口,允许像您的 这样的强制类型转换。

您可以在.NET documentation中找到大量有关协方差和协方差的文档。

答案 1 :(得分:1)

为什么也不要添加非通用接口:

interface IInterface { void Run(IParameter input); }

然后让您的通用接口扩展此非通用接口。

很明显,您的实现应该强制转换IParameter,有人需要强制转换...您可以创建一个抽象基类来为您执行此操作,因此并非每个实现都必须执行此操作。

您可能还对双重派发模式感兴趣,尽管我不确定这是否适用于您的情况。