C# 无法将“System.Collections.Generic.List`1[Item]”类型的对象转换为“ItemList”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1882520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 21:37:16  来源:igfitidea点击:

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

c#

提问by PositiveGuy

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.

出于某种原因,我的老板喜欢创建自定义类型来表示通用列表(即使在大多数情况下,他的自定义类型没有成员!我认为他只是懒惰,不喜欢键入 List 之类的东西,但对我来说这是跛脚,每个下面的问题让我很头疼。

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 standard 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

因此,当我使用标准列表时(也许我讨厌他的自定义类,喜欢使用应该使用的普通 .NET 类型),或者也许我正在使用如下所示的 LINQ 表达式,我总是遇到强制转换问题即使自定义类型是从该 List 继承的

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

    return itemList;
    ....
}

采纳答案by Lee

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:

正如Grzenio 指出的那样,您不能使用 ToList() 和强制转换,但是您可以创建自己的扩展方法来从序列创建派生类型的实例:

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>();

回答by Grzenio

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.

不幸的是,ToList() 将返回一个普通列表,而不是 ItemnList,因此您无法投射它。我真的没有看到合理的解决方法,最好将 List 封装在 ItemnList 中,而不是从中派生。