简体   繁体   中英

There is no implicit reference conversion from 'Type' to 'Interface'

I have three interfaces:

internal interface IAmAnInterfaceOne
{
    int PropertyOne { get; set; }
}

internal interface IAmAnInterfaceTwo
{
    int PropertyTwo { get; set; }
}

internal interface IAmAnInterfaceCombiningOneAndTwo : IAmAnInterfaceOne, IAmAnInterfaceTwo
{
}

Implementation class:

internal class Myimplementation : IAmAnInterfaceOne, IAmAnInterfaceTwo
{
    public int PropertyOne { get; set; }
    public int PropertyTwo { get; set; }
}

When I tried to bind interface IAmAnInterfaceCombiningOneAndTwo to Myimplementation , I got error:

There is no implicit reference conversion from 'Type' to 'Interface'

class AppModule : NinjectModule
{
    public override void Load()
    {
        Bind<IAmAnInterfaceCombiningOneAndTwo>().To<Myimplementation>().InSingletonScope();
    }
}

I want to use it in constructor like that:

public class MyClass
{
    private readonly IAmAnInterfaceCombiningOneAndTwo _param;

    public MyClass(IAmAnInterfaceCombiningOneAndTwo param)
    {
        _param = param;
    }
}

How to bind interface properly? Thanks.

This is not a Ninject error.

IAmAnInterfaceCombiningOneAndTwo obj = new Myimplementation();

The above code wouldn't compile. Why? Because Myimplementation doesn't implement IAmAnInterfaceCombiningOneAndTwo . It implements IAmAnInterfaceOne and IAmAnInterfaceTwo .

IAmAnInterfaceCombiningOneAndTwo requires that these two are implemented, but merely implementing them doesn't also mean that the implementer implements the combination interface. It's technically a different interface altogether. Indeed, you could add further requirements to the combination interface that neither IAmAnInterfaceOne nor IAmAnInterfaceTwo include.

The simplest solution is to change Myimplementation to explicitly declare that it implements the combination interface (either additionally, or just that interface - the net effect is the same):

internal class Myimplementation : IAmAnInterfaceCombiningOneAndTwo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM