简体   繁体   中英

Type mismatch in variable assignment to generics based variable

Does anyone know why C# doesn't seem to like the following bit of code?

The issue is that MyContext cannot be assigned to the _context variable due to its type mismatch, however MyContext derives (inherits?) from DbContext , so that should satisfy the generics where clause, surely?

public class UnitOfWork<TContext> : IUnitOfWork<TContext> where TContext : DbContext
{
    private TContext _context;

    public UnitOfWork()
    {
        _context = new MyContext(Common.ConfigurationProvider.DatabaseConnectionString);
    }
...

}

This is not allowed because where TContext : DbContext constraint promises that TContext will be of DbContext and not MyContext .

In other words TContext may be MyContext2 which have no inheritance relationship with MyContext . So compiler is not happy with that :(

If you're going to use specific context MyContext then IMO you don't need generics.


Edit: If you're sure that your context will be descendant of type argument(TContext) then you can play a trick to make it work,

 public UnitOfWork() { _context = (TContext)(object)new MyContext(...); } 

but, I will think twice before using this in production code. This will fail if MyContext is not TContext or descendant of it.

TContext可能是另一种类型继承DbContext与类型不相容MyContext

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