C# Cannot convert from IEnumerable<Base> to IEnumerable

后端 未结 4 583
忘掉有多难
忘掉有多难 2020-12-19 07:53

I recently run into trouble when trying to AddRange(IEnumerable) to a List. Probably a classic issue, but I do not really get it yet.

I understand that methods expec

4条回答
  •  感动是毒
    2020-12-19 08:36

    The cast solution of course might generated class cast exceptions. The person who posted the enumerable extension work around said it was awkward. I came up with a solution which is only half as awkward, don't know if I'll use it:

    public static class UpTo
    {
        public static IEnumerable From(IEnumerable source) where F:T
        {
            // this cast is guaranteed to work
            return source.Select(f => (T) f);
        }
    }
    

    Usage:

    IEnumerable mammals = UpTo.From(kennel.Dogs)

提交回复
热议问题