简体   繁体   中英

Generic method type can't be used as generic type for generic class

I want to implement a generic method that should create an instance of a double generic object. The generic types of this class that should be instantiated are another class and an interface which the first type must implement. When I call new in the generic method with its generic type I get the compiler error CS0311 even if I restrict the type correctly to my base interface. Why can't I create an instance like this?

class Program
{

    static void Main(string[] args)
    {
        GetQuery<ITESTEntity>();
    }

    static void GetQuery<I>() where I : IEntityBase
    {
        var qry = new myQuery<TESTEntity, I>();
    }
}

class myQuery<T, I> 
    where T : class, I
    where I : IEntityBase
{

}

Assuming you have these definitions:

interface IEntityBase { }

interface ITESTEntity : IEntityBase { }

class TESTEntity : ITESTEntity { }

Then your problem stems from here:

class myQuery<T, I> 
    where T : class, I
    where I : IEntityBase

You're stating that T must be assignable to I , and I must be assignable to IEntityBase . That's fine, but here:

static void GetQuery<I>() where I : IEntityBase
{
    var qry = new myQuery<TESTEntity, I>();

You're accepting any I that's assignable to IEntityBase . So you could also call it like this:

interface ITESTEntity2 : IEntityBase { }

class TESTEntity2 : ITESTEntity2 { }

GetQuery<ITESTEntity2>();

This call would be valid, but now in your method GetQuery() :

new myQuery<TESTEntity, I>();

I will be ITESTEntity2 , to which TESTEntity is not assignable. It can't be guaranteed that TESTEntity is assignable to any I where I is assignable to IEntityBase , as demonstrated above with ITESTEntity2 .

So reconsider your design.

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