开发者

Unable to cast object of type 'System.Collections.Generic.List`1[Item]' to type 'ItemList'

开发者 https://www.devze.com 2022-12-13 21:38 出处:网络
For some reason, my boss likes to create custom types to represent a generic list(even in most cases where his custom type has no members!I think he\'s just lazy and doesn\'t like to type the List or

For some reason, my boss likes to create custom types to represent a generic list (even in most cases where his custom type has no members! I think he's just lazy and doesn't like to type the List or something but to me this is lame and is causing me many headaches per the issue below.

Point in case:

public class ItemnList : List<Item>
{
    public Personalization FindById(int id)
    {
        ...blahblah blah, this is really an extension method that should be elsewhere
    }

}

Consequently, when I'm using a standar开发者_运维百科d List (mabye I hate his custom class and like to use plain .NET types like they should be used), OR maybe I'm using a LINQ expression like below, I always run into casting problems even though the custom type is inheriting from that List

private ItemList someMethod(ItemList itemList)
{
    ...
    itemList = (ItemList)items.Where(x => x.ItemType != ItemType.Car && x.ItemType != ItemType.Truck).ToList();

    return itemList;
    ....
}


As Grzenio points out, you can't use ToList() and cast, however you could create your own extension method to create an instance of the derived type from a sequence:

public static TDerived CreateFromEnumerable<TDerived, T>(this IEnumerable<T> seq) where TDerived : List<T>, new()
        {
            TDerived outList = new TDerived();
            outList.AddRange(seq);
            return outList;
        }

So for your example you would do:

ItemList outList = itemList
    .Where(x => x.ItemType != ItemType.Car && x.ItemType != ItemType.Truck)
    .CreateFromEnumerable<ItemList, Item>();


Unfortunately ToList() will return a normal list, and not ItemnList, so you can't cast it. I don't really see a reasonable workaround, it would probably be better to encapsulate the List in ItemnList, instead deriving from it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号