相关疑难解决方法(0)

为什么IEnumerable <T>没有实现Add(T)?

刚刚发现它,Add(T)定义在ICollection<T>,而不是IEnumerable<T>.Enumerable.cs中的扩展方法不包含Add(T),我认为这很奇怪.由于对象是可枚举的,因此它必须"看起来像"一组项目.谁能告诉我为什么?

.net c# generics collections ienumerable

12
推荐指数
3
解决办法
2989
查看次数

C#列表通用扩展方法与非通用扩展方法

这是一个简单的问题(我希望),在集合类中有泛型和非泛型方法,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)

为什么使用一个(通用或非通用)?

c# generics collections

7
推荐指数
1
解决办法
707
查看次数

将通用扩展方法添加到IEnumerable等接口

我一直在尝试并尝试使我的通用扩展方法工作,但他们只是拒绝,我无法弄清楚为什么. 虽然它应该,但这个帖子对我没有帮助.

当然我已经查到了如何,在我看到他们说它很简单的时候应该是这样的语法:(
在某些地方我读到我需要在参数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)

它给出了这个错误:

必须在非泛型静态类中定义扩展方法

任何帮助将不胜感激,我真的被困在这里.

c# generics extension-methods

6
推荐指数
1
解决办法
1228
查看次数