【问题标题】:Short hand to copy properties from parent to child将属性从父级复制到子级的简写
【发布时间】:2020-03-19 22:35:55
【问题描述】:

我有以下类结构:

    public class Parent
    {
        public int Property1;
        public int Property2;
        public int Property3;
        //Lots more properties
    }

    public class Child : Parent
    {
        public int Property80;
    }

还有这样的父母名单:

var parentList = new List<Parent>
        {
            //Some data....
        };

我现在想创建一个新的子列表,其中包含来自parentList 的所有数据

我知道我可以做到:

var childList = parentList.Select(x => new Child { Property1 = x.Property1, Property2 = x.Property2, //etc }

但我的问题是,是否有一种速记或单行方式来执行此操作,以免我不得不写出一大串属性?

【问题讨论】:

标签: c# list inheritance casting copy


【解决方案1】:

当您创建Parent 列表时,使用Child

var parentList = new List<Parent>
{
    new Child { Property1 = 1, Property2 = 2, Property3 = 3 },
    new Child { Property1 = 4, Property2 = 5, Property3 = 6 },
    new Child { Property1 = 7, Property2 = 8, Property3 = 9 }
};

这相当于Parent p = new Child { Property1 = 1, Property2 = 2, Property3 = 3 }

现在您可以将其转换为 Child 并在 Select 中添加缺少的属性

var childList1 = parentList.Select(x => { Child y = (Child)x; y.Property80 = 80; return y; });

【讨论】:

    猜你喜欢
    • 2018-05-17
    • 2021-06-28
    • 2022-09-30
    • 1970-01-01
    • 2021-11-05
    • 2018-01-15
    • 1970-01-01
    • 1970-01-01
    • 2018-06-14
    相关资源
    最近更新 更多