public static class ListExten<T>
{
public static IList<T> ForeachOne(this IList<T> eles, Action<T> act)
{
foreach (T e in eles)
{
if (act != null)
{
act(e);
}
}
return eles;
}
}
为什么Error 26 Extension method must be defined in a non-generic static class
大哥,你用Google翻译就知道Extension method must be defined in a non-generic static class 的意思是 扩展方法必须在非泛型静态类中定义。
扩展方法是静态方法,而且扩展方法是加载到this中的使用的,也就是说和定义此方法的类没有关系,所以你类中定义泛型,在使用时没办法设置泛型参数
一般泛型类静态方法调用
ListExten<string>.ForeachOne()
泛型参数通过类传递到方法
而扩展方法完全隐藏了ListExten类所以无法通过类传递泛型参数。
应该定义到方法上,
static IList<T> foreachOne<T>(this IList<T> list)
就可以通过
List<string>.foreachOne<string>()
简写成
List<string>.foreachOne()