简体   繁体   中英

Cannot convert IEnumerable<T> to IEnumerable<T> for different mscorlib versions

I'm messing with a few generic classes in which I have a collection class which contains a method to load objects from a DTO collection, fetching the child objects using a 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??
    }

(the C is constrained on the class def)

Everything else is working fine - but I get the message that I can't convert a C to a C. If I remove the this.Add and debug, checking the type after it's fetched; it returns a C ( item is C = true), trying to add that to the list however throws invalid arguments even though the constraint on the list is on that very C.

Attempting to use this.AddRange also doesn't work citing IEnumerable<T> v4.0.0.0 cannot be assigned to IEnumerable<T> v2.0.5.0 (note the diff versions of mscorlib)

Is there an easy way to find out what's referencing the older mscorlib? Anyone else had this issue?

I suspect the problem is one like this:

class MyCollection<C>
{
    private List<C> list = new List<C>();

    public void Add<C>(C item)
    {
        list.Add(item);
    }
}

Note that both MyCollection and Add declare a type parameter called C . This will result in a warning like this even without the call to 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)

The Add call will have errors like this:

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)

This has nothing to do with the mscorlib differences, which may or may not still be an issue.

Moral: heed compile-time warnings! They can give you clues to other errors. Warnings in C# are sufficiently rare that you should almost always have warning-free code.

Always answer my own question 5 seconds after posting :(

Realised I was constraining C again in the LoadCollection method

Changing to this fixed it:

   public void LoadCollection<D>(IEnumerable<D> dtos, Func<D, C> fetch)
        where D : class
    {
        foreach (var dto in dtos)
            this.Add(fetch(dto));
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM