在c#中创建泛型对象的泛型列表

本文关键字:泛型 对象 列表 创建 | 更新日期: 2023-09-27 18:14:46

我有一个泛型类,我想为它创建一个泛型列表,其中底层类实现相同的接口。然而,并不是所有的都实现了给定的接口。

举例比描述问题更容易。

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};**
    }

}

我无法创建thingList。是否有一种方法可以将实现相同接口的两个东西强制转换为泛型集合,同时仍然保持GenericThing类不受接口的约束?

在c#中创建泛型对象的泛型列表

如果使用协变接口,这是可能的:

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};
}

注意,这只有在T只被用作IGenericThing<T>的输出,而不是作为输入时才有可能!(如在我的例子中,它未被使用也是允许的;