简体   繁体   中英

How to assign a concrete implementation of generic type to list of generic type

I have been trying to understand why the following generates a compile error, and how to get around the error.

public interface IA { }
public class AImp : IA { }

public interface IConsumer<T> where T : IA
{
    void Consume(T val);
}

public class Consumer : IConsumer<AImp>
{
    public void Consume(AImp val)
    {
        // do smth
    }
}

public class Program
{
    public static void Main()
    {
        IList<IConsumer<IA>> l1 = new List<IConsumer<IA>>();
        l1.Add(new Consumer());  // generate compile error cannot convert from consumer to IConsumer<IA>

    }
}

If I can create IList<IA> l = new List<IA>(); and asign l.Add(new AImp()); , I dont see why the generic type is not working. Perhaps I am missing something fundamental.

I haven't been able to find any promising leads from google either.

You get an error message because the Consumer does not inherit from IConsumer<T>. It inherits from IConsumer<AImp>.

There is special technique to use this kind of template class, you have to create a IConsumer interface which is not generic type like this:

public interface IA { }
public class AImp : IA { }

public interface IConsumer
{
}

public interface IConsumer<T> : IConsumer
    where T : IA
{
    void Consume(T val);
}

public class Consumer : IConsumer<AImp>
{
    public void Consume(AImp val)
    {
        // do smth
    }
}

public class Program
{
    public static void Main()
    {
        IList<IConsumer> l1 = new List<IConsumer>();
        l1.Add(new Consumer());  // ok
    }
}

This basically the idea behind the IEnumerable and ICollection generic and non generic versions.

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