简体   繁体   中英

Create a Generic List of Generic objects in C#

I have a generic class for which I would like to create a generic list, where the underlying classes implement the same interface. However, not all implement the given interface.

An example would be easier than describing the problem.

internal interface ISomething
{

}

internal class ThisThing : ISomething
{
}

internal class ThatThing : ISomething
{

}

internal class SomethingElse 
{

}

internal class GenericThing<T> 
{

}

internal class DoThings
{
    void Main()
    {
        var thing1 = new GenericThing<ThisThing>();
        var thing2 = new GenericThing<ThatThing>();

        var thing3 = new GenericThing<SomethingElse>();

        **var thingList = new List<GenericThing<ISomething>>() {thing1, thing2};**
    }

}

I'm unable to create the thingList. Is there a way to cast the two things that implement the same interface into a generic collection, while still preserve the GenericThing class not to be constrained to the interface.

This is possible if you use a covariant interface :

internal interface IGenericThing<out T>
{
}

internal class GenericThing<T> : IGenericThing<T>
{
}

void Main()
{
    var thing1 = new GenericThing<ThisThing>();
    var thing2 = new GenericThing<ThatThing>();

    var thing3 = new GenericThing<SomethingElse>();

    var thingList = new List<IGenericThing<ISomething>>() {thing1, thing2};
}

Note that this is only possible if T is only used as an output in IGenericThing<T> , never as an input! (it being unused, as in my example, is also permissible; although, obviously, useless)

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