【发布时间】:2010-12-23 06:38:06
【问题描述】:
我希望能够编写以下代码:
// contains 500 entries
IList<string> longListOfStrings = ...
// shorterListsOfStrings is now an array of 5 IList<string>,
// with each element containing 100 strings
IList<string>[] shorterListsOfStrings = longListOfStrings.Split(5);
为此,我必须创建一个名为 Split 的通用扩展方法,如下所示:
public static TList[] Split<TList>(this TList source, int elementCount)
where TList : IList<>, ICollection<>, IEnumerable<>, IList, ICollection, IEnumerable
{
return null;
}
但是当我尝试编译它时,编译器告诉我IList<>、ICollection<> 和IEnumerable<> 需要一个类型参数。因此,我将定义更改为:
public static TList<TType>[] Split<TList<TType>>(this TList<TType> source, int elementCount)
where TList : IList<TType>, ICollection<TType>, IEnumerable<TType>, IList, ICollection, IEnumerable
{
return null;
}
然后编译器抱怨它找不到类型TList。我有一个想法,我把事情复杂化了,但我看不出……任何帮助都值得赞赏!
【问题讨论】:
标签: c# generics .net-3.5 extension-methods