简体   繁体   中英

Casting implementation to the interface with generic type

My company has a shared library that has code like this

public interface IBaseService<TBaseUser> where TBaseUser : BaseUser
{
   // snip
}

public class User : BaseUser
{
    // snip
}

public class SomeService : IBaseService<User>
{

}

Various applications make use of this shared code. I am trying to write a base controller that takes in an IBaseService<BaseUser> in its ctor.

public class BaseController : Controller
{
    public BaseController(IBaseService<BaseUser> service)
    { 
    }
}

The code at the library level works exactly as I'd expect, but when I try to use it from a consuming application and pass in the derived type, ie a Service type, it fails with an invalid cast.

public class MyController : BaseController
{
    public MyController(SomeService service) : base(service)
    {
    }
}

Is what I want to do possible?

Your IBaseService -iterface needs to be covariant :

interface IBaseService<out T> 

This way you can assign an instance of IBaseService<User> to IBaseService<BaseUser> .

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