C# IList<;T>;其中T是泛型类

C# IList<;T>;其中T是泛型类,c#,.net,generics,C#,.net,Generics,我需要创建一个通用IList,其中T是一个具有各种接口的通用类。 例如ChannelFactory或ChannelFactory等..这是怎么回事 public class MyList<T>: IList<T> where T: class { } public类MyList:IList其中T:class { } 如果需要,应在必要时更改设计。使所有接口都从同一接口派生,例如IServiceBase。然后,可以对泛型类使用以下约束: IList<T> wh

我需要创建一个通用IList,其中T是一个具有各种接口的通用类。 例如
ChannelFactory
ChannelFactory
等..

这是怎么回事

public class MyList<T>: IList<T> where T: class
{
}
public类MyList:IList其中T:class
{
}

如果需要,应在必要时更改设计。使所有接口都从同一接口派生,例如
IServiceBase
。然后,可以对泛型类使用以下约束:

IList<T> where T: IServiceBase
IList其中T:IServiceBase
您可以执行以下操作:

IList<ChannelFactory<IService1>> list = new List<ChannelFactory<IService1>>;
IList list=新列表;
但您不能混合和匹配此列表中的ChannelFactory和ChannelFactory对象

如果您确实需要在列表中进行混合和匹配,请使用非通用的:

IList non_generic_list = new List();
non_generic_list.Add(new ChannelFactory<IService1>());
non_generic_list.Add(new ChannelFactory<IService2>());
IList非通用列表=新列表();
非通用列表。添加(新ChannelFactory());
非通用列表。添加(新ChannelFactory());
您可以这样做:

var list = new List<ChannelFactory<IService1>>();
var list=newlist();

事实上,您可以任意嵌套泛型,但过一段时间后您可能会厌倦所有的尖括号。

如果您需要在运行时从动态类型创建列表,您可以像这样创建泛型列表类型

public IList CreateList(Type interfaceType)
        {
            return (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(interfaceType));
        }
public IList CreateList(类型interfaceType)
{
return(IList)Activator.CreateInstance(typeof(List).MakeGenericType(interfaceType));
}
然后你可以做:

IList<ChannelFactory<IService1>> list = CreateList(typeof(ChannelFactory<IService1>)) as IList<ChannelFactory<IService1>>;
IList list=CreateList(typeof(ChannelFactory))作为IList;

如果您知道在何时何地需要哪个泛型类,那么可以使用接口层次结构。如果您不能完全控制这个问题,但需要在运行时动态创建列表,这可能是一个解决方案。

我认为他需要一个泛型类,该类可以接受多个接口,并对接口类型进行约束。接口层次结构是一个确定的方法。