向下转换C#中的对象列表 [英] Downcasting a list of objects in C#

查看:74
本文介绍了向下转换C#中的对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何向下转换对象列表,以便将列表中的每个对象向下转换为派生类的对象?

How can I downcast a list of objects so that each of the objects in the list is downcast to an object of a derived class?

这是场景.

我有一个带有List基本项目的基类,并且有两个继承自它的类:

I have a base class with a List of base items, and two classes inheriting from it:

public class BaseClass
{
    public List<BaseItem> items;
    protected BaseClass()
    {
        // some code to build list of items
    }
}
public class DerivedClass : BaseClass
{
    public DerivedClass : base() {}
}
public class AnotherDerivedClass : BaseClass
{
    public AnotherDerivedClass : base() {}
}

public class BaseItem {}
public class DerivedItem : BaseItem {}
public class AnotherDerivedItem : BaseItem {}

想法是不必重复构建项目列表所需的代码. BaseItem具有我需要的所有基本内容,我总是可以将BaseItem下放到其中一个派生项目中.

The idea is to not have to duplicate the code needed to build the list of items. The BaseItem has all the basic stuff I need, and I can always downcast BaseItem to one of the derived items.

当我列出它们时,就会出现问题.在BaseClass中声明BaseItemList,因为所有派生类都必须具有它.但是在运行时访问它时,我似乎无法向下转换到派生类.

The problem arises when I have a list of them. The List of BaseItem is declared in the BaseClass because all the derived classes have to have it. But when accessing it at runtime I can't seem to be able to downcast to the derived class.

推荐答案

使用LINQ:

    var baseList = new List<BaseClass>();
    var derivedList = baseList.Cast<DerivedClass>();

注意:通常必须低调处理是一种气味",它表示继承层次结构是错误的,或实现不正确.具有基类的想法是,您可以将所有子类都视为超类,而不必向下转换为单个子类类型.

Note: Having to downcast usually is a 'smell' and indicates that the inheritance hierarchy is wrong, or wrongly implemented. The idea of having a base class is that you can treat all subclasses as superclass without having to downcast to individual subclass types.

您可能想使用OfType而不是Cast从超类集合中探出"某些派生类.但是同样,没有必要这样做.

Instead of Cast you might want to use OfType to 'fish out' certain derived classes from a collection of superclasses. But again, there should be no need to do that.

问问自己,为什么需要一个子类-也许您需要将某些功能移至基类?

Ask yourself, why you need to have a subclass - maybe you need to move some functionality to base class?

这篇关于向下转换C#中的对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆