我收到编译错误错误“无法找到类型或命名空间名称'T'(您是否缺少using指令或程序集引用?
以下是我的代码:
static class ExtensionMethods
{
public static Collection<T> ToCollection(this IEnumerable<T> source)
{
Collection<T> sourceCollection = new Collection<T>();
foreach (T currentSourceInstance in source)
{
sourceCollection.Add(currentSourceInstance);
}
return sourceCollection;
}
}
答案 0 :(得分:14)
将其更改为:
public static class ExtensionMethods
{
public static Collection<T> ToCollection<T>(this IEnumerable<T> source)
{
Collection<T> sourceCollection = new Collection<T>();
foreach (T currentSourceInstance in source)
{
sourceCollection.Add(currentSourceInstance);
}
return sourceCollection;
}
}
注意ToCollection<T>
,否则编译器无法理解T
的来源。
您可以这样调用它(在此示例中Thing
是您的自定义类型):
var items = new List<Thing>();
var collection = items.ToCollection<Thing>();