gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:14:24 24 4
gpt4 key购买 nike

我有以下扩展方法:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com