[英]Cannot convert IEnumerable<T> to IEnumerable<T> for different mscorlib versions
我搞砸了一些通用类,其中有一个收集类,该收集类包含一个从DTO收集中加载对象的方法,并使用Func
获取子对象
public void LoadCollection<C, D>(IEnumerable<D> dtos, Func<D, C> fetch)
where D : class
{
foreach (var dto in dtos)
this.Add(fetch(dto)); // Can't assign a C to a C??
}
(C限制在def类上)
其他一切工作正常-但我收到消息,我无法将C转换为C。如果我删除了this.Add
并调试,在提取类型后检查类型; 它返回一个C( item is C
= true),尝试将其添加到列表中,但是即使该列表上的约束位于该C上,也会引发无效参数。
尝试使用this.AddRange
也不起作用,因为无法将IEnumerable<T> v4.0.0.0
分配给IEnumerable<T> v2.0.5.0
(请注意mscorlib的差异版本)
有没有一种简单的方法来找出引用旧mscorlib的东西? 其他人有这个问题吗?
我怀疑问题是这样的:
class MyCollection<C>
{
private List<C> list = new List<C>();
public void Add<C>(C item)
{
list.Add(item);
}
}
请注意, MyCollection
和Add
声明了一个名为C
的类型参数。 即使没有调用Add
也会导致这样的警告:
Test.cs(8,21): warning CS0693: Type parameter 'C' has the same name as the type
parameter from outer type 'MyCollection<C>'
Test.cs(4,20): (Location of symbol related to previous warning)
Add
调用将出现以下错误:
Test.cs(10,9): error CS1502: The best overloaded method match for
'System.Collections.Generic.List<C>.Add(C)' has some invalid arguments
Test.cs(10,18): error CS1503: Argument 1: cannot convert from 'C
[c:\Users\Jon\Test\Test.cs(4)]' to 'C'
Test.cs(8,21): (Location of symbol related to previous error)
这与mscorlib的差异无关,这可能是也可能不是问题。
道德:注意编译时警告! 他们可以为您提供其他错误的线索。 C#中的警告非常少见,因此您几乎总是应具有免警告代码。
发布后5秒钟,务必回答我自己的问题:(
LoadCollection
我在LoadCollection
方法中再次约束了C
更改为此固定它:
public void LoadCollection<D>(IEnumerable<D> dtos, Func<D, C> fetch)
where D : class
{
foreach (var dto in dtos)
this.Add(fetch(dto));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.