mercredi 17 octobre 2018

.NET Core Cast to interface with generic type parameter of type which implements interface

In .NET Core C# I' trying something like this:

(IInterface<IParameter>)instance

Where instance is new Implementation<Parameter>()

And Implementation : IInterface & Parameter : IParameter

The issue is with the casting of the generic parameter. When I provide Parameter instead of IParameter it works but at compile time there is no way to know which type that implements IParameter will be used. All of these objects will be created via reflection.

So is there any way this cast works? Or some other way to implement this like providing no generic type parameter like you can with typeof.

Full example:

interface IInterface<TInput>
    where TInput : IParameter
{
    void Run(TInput input);
}

interface IParameter {}

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

class Parameter : IParameter {}

class Program
{
    static void Main()
    {
        object instance = new Implementation();
        var castInstance = (IInterface<IParameter>) instance; // This will crash
        castInstance.Run(new Parameter());
    }
}





Aucun commentaire:

Enregistrer un commentaire