2009-12-22 35 views
0

我需要创建一个通用IList,其中T将是一个具有各种接口的泛型类。 例如ChannelFactory<IService1>ChannelFactory<IService2>等。IList <T>其中T是通用类

+2

这里有问题吗? – leppie 2009-12-22 09:20:29

+1

我想他想要一个接受带有接口类型约束的多个接口的泛型类。 – 2009-12-22 09:21:44

回答

7

如果你想这样做,你应该改变你的设计,如果有必要。使所有接口都来自相同的接口,例如IServiceBase。然后,可以使用以下约束你的泛型类:

IList<T> where T: IServiceBase 
+0

界面层次结构是确定的方式。 – Codesleuth 2009-12-22 09:22:48

1

这是怎么回事?

public class MyList<T>: IList<T> where T: class 
{ 
} 
1

你可以这样做:

IList<ChannelFactory<IService1>> list = new List<ChannelFactory<IService1>>; 

但你不能混用,并在本场比赛的ChannelFactory < IService1>和的ChannelFactory < IService2>对象名单。

如果你真的需要混合和匹配列表中使用非通用的一个:

IList non_generic_list = new List(); 
non_generic_list.Add(new ChannelFactory<IService1>()); 
non_generic_list.Add(new ChannelFactory<IService2>()); 
0

你可以只是这样做:

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

事实上,你可以嵌套泛型尽可能多的,但你可能会在一段时间后对所有尖括号感到厌倦。

1

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

public IList CreateList(Type interfaceType) 
     { 
      return (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(interfaceType)); 
     } 

然后,你可以这样做:

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

如果你有知识,通用类的,你需要的时间和地点,去的接口层次结构。如果您没有完全控制它,但需要在运行时动态创建列表,这可能是一个解决方案。