c# - 未找到扩展方法(不是程序集引用问题)

标签 c# linq extension-methods

我有以下扩展方法:

public static EntitySet<T> ToEntitySetFromInterface<T, U>(this IList<U> source)
    where T : class, U
{
    var es = new EntitySet<T>();
    IEnumerator<U> ie = source.GetEnumerator();
    while (ie.MoveNext())
    {
        es.Add((T)ie.Current);
    }
    return es;
}

我正在尝试按如下方式使用它:

   List<IItemMovement> p = new List<IItemMovement>();
    EntitySet<ItemMovement> ims = p.ToEntitySetFromInterface<ItemMovement, IItemMovement>();

ItemMovement 实现了 IItemMovement。编译器提示:

'System.Collections.Generic.List' does not contain a definition for 'ToEntitySetFromInterface' and no extension method 'ToEntitySetFromInterface' accepting a first argument of type 'System.Collections.Generic.List' could be found (are you missing a using directive or an assembly reference?)

不,我没有遗漏引用资料。如果我只键入包含它弹出的方法的静态类的名称,扩展方法也是如此。谢谢

最佳答案

这段代码对我有用,它是您代码的直接副本,减去了 ItemMovement 及其接口(interface),所以这部分可能有问题吗?

public class TestClient
{
    public static void Main(string[] args)
    {
        var p = new List<IItem>();
        p.Add(new Item { Name = "Aaron" });
        p.Add(new Item { Name = "Jeremy" });

        var ims = p.ToEntitySetFromInterface<Item, IItem>();

        foreach (var itm in ims)
        {
            Console.WriteLine(itm);
        }

        Console.ReadKey(true);
    }
}

public class Item : IItem
{
    public string Name { get; set; }
    public override string ToString()
    {
        return Name;
    }
}

public interface IItem
{
}

public static class ExtMethod
{
    public static EntitySet<T> ToEntitySetFromInterface<T, U>(this IList<U> source) where T : class, U
    {
        var es = new EntitySet<T>();
        IEnumerator<U> ie = source.GetEnumerator();
        while (ie.MoveNext())
        {
            es.Add((T)ie.Current);
        }
        return es;
    }
}

关于c# - 未找到扩展方法(不是程序集引用问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9582618/

相关文章:

c# - 无边框窗口无法正确最大化

c# - Visual Studio 测试服务器上的 Server.TransferRequest

c# - 命名空间、别名和 Visual Studio Forms Designer

c# - 将 Linq 表达式添加到表达式列表的方法

c# - 使用 C# Linq 表达式自定义排序

c# - 结构上的扩展方法

c# - 如何知道 virtual\override 中的大多数派生实现

c# - 在 linq 中使用 ANY 条件处理 WHERE 内的空值

c# - 我如何模拟或类似地注入(inject)对应用于 NHibernate session 的查询扩展方法的替换

.net - 创建将字符串转换为可为空的数字的通用方法