本文介绍了复制一个List< BaseClass的>列出< D​​erivedClass>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的类定义:

 公共类BaseClass的
{
    公共字符串SomeProp1 {获得;组; }
}

公共类DerivedClass:BaseClass的
{
    公共字符串SomeProp2 {获得;组; }
}
 

我如何可以采取名单,其中,BaseClass的> 键,将其转换为名单,其中,DerivedClass>

在我的现实世界中的场景的BaseClass 有一大堆的属性,我不希望有复制了一个接一个(然后记得保持如果一个附加属性被添加)。

添加一个参数化的构造函数的BaseClass 是不是因为这个类是由一个WCF服务引用定义的选项。

解决方案

 名单,其中,DerivedClass>结果=
    listBaseClass.ConvertAll(例如=>(DerivedClass)实例);
 

其实,当你需要创建在原有基础上,当你只是需要转换,你可以使用下面的新对象ConvertAll好

 名单,其中,DerivedClass>结果=
    listBaseClass.Cast&其中; DerivedClass>();
 

Given the following class definitions:

public class BaseClass
{
    public string SomeProp1 { get; set; }
}

public class DerivedClass : BaseClass
{
    public string SomeProp2 { get; set; }
}

How can I take a List<BaseClass> and convert it to a List<DerivedClass>?

In my real-world scenario BaseClass has a whole bunch of properties that I don't want to have to copy over one-by-one (and then remember to maintain if an additional property gets added).

Adding a parameterised constructor to BaseClass is not an option as this class is defined by a WCF service reference.

解决方案
List<DerivedClass> result =
    listBaseClass.ConvertAll(instance => (DerivedClass)instance);

Actually ConvertAll is good when you need to create new objects based on the original, when you just need to cast you can use the following

List<DerivedClass> result =
    listBaseClass.Cast<DerivedClass>();

这篇关于复制一个List&LT; BaseClass的&GT;列出&LT; D​​erivedClass&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 15:45