c# – 找不到扩展方法(不是程序集引用问题)
作者:互联网
我有以下扩展方法:
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?)
不,我没有错过参考.如果我只输入包含弹出方法的静态类的名称,那么扩展方法也是如此.日Thnx
解决方法:
这段代码适用于我,它是代码的直接副本,减去ItemMovement及其界面,所以这个部分可能有问题吗?
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,linq,extension-methods 来源: https://codeday.me/bug/20190630/1334758.html