繁体   English   中英

获取错误找不到类型或命名空间名称“T”(您是否缺少using指令或程序集引用?)

[英]Getting error The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?)

我收到编译错误错误“无法找到类型或命名空间名称'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;
    }
} 

把它改成这个:

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>();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM