Rik*_*ter 6 c# generics extension-methods
我一直在尝试并尝试使我的通用扩展方法工作,但他们只是拒绝,我无法弄清楚为什么. 虽然它应该,但这个帖子对我没有帮助.
当然我已经查到了如何,在我看到他们说它很简单的时候应该是这样的语法:(
在某些地方我读到我需要在参数decleration之后添加"where T:[type]",但是我的VS2010只是说这是一个语法错误.)
using System.Collections.Generic;
using System.ComponentModel;
public static class TExtensions
{
public static List<T> ToList(this IEnumerable<T> collection)
{
return new List<T>(collection);
}
public static BindingList<T> ToBindingList(this IEnumerable<T> collection)
{
return new BindingList<T>(collection.ToList());
}
}
Run Code Online (Sandbox Code Playgroud)
但这不起作用,我得到这个错误:
找不到类型或命名空间名称"T"(您是否缺少using指令或程序集引用?)
如果我然后更换
public static class TExtensions
Run Code Online (Sandbox Code Playgroud)
通过
public static class TExtensions<T>
Run Code Online (Sandbox Code Playgroud)
它给出了这个错误:
必须在非泛型静态类中定义扩展方法
任何帮助将不胜感激,我真的被困在这里.
Jon*_*eet 14
我认为你所缺少的是使方法通用T:
public static List<T> ToList<T>(this IEnumerable<T> collection)
{
return new List<T>(collection);
}
public static BindingList<T> ToBindingList<T>(this IEnumerable<T> collection)
{
return new BindingList<T>(collection.ToList());
}
Run Code Online (Sandbox Code Playgroud)
请注意<T>参数列表之前的每个方法的名称.这说明它是一个带有单一类型参数的通用方法T.