刚刚发现它,Add(T)定义在ICollection<T>,而不是IEnumerable<T>.Enumerable.cs中的扩展方法不包含Add(T),我认为这很奇怪.由于对象是可枚举的,因此它必须"看起来像"一组项目.谁能告诉我为什么?
这是一个简单的问题(我希望),在集合类中有泛型和非泛型方法,List<T>比如具有Where和等方法Where<T>.
例:
List<int> numbers = new List<int>()
{
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
};
IEnumerable<int> evens = numbers.Where((x) =>
{
return x % 2 == 0;
});
IEnumerable<int> evens2 = numbers.Where<int>((x) =>
{
return x % 2 == 0;
});
Run Code Online (Sandbox Code Playgroud)
为什么使用一个(通用或非通用)?
我一直在尝试并尝试使我的通用扩展方法工作,但他们只是拒绝,我无法弄清楚为什么. 虽然它应该,但这个帖子对我没有帮助.
当然我已经查到了如何,在我看到他们说它很简单的时候应该是这样的语法:(
在某些地方我读到我需要在参数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)
它给出了这个错误:
必须在非泛型静态类中定义扩展方法
任何帮助将不胜感激,我真的被困在这里.