简体   繁体   English

将属性从父级复制到子级的简写

[英]Short hand to copy properties from parent to child

I have the following class tructure:我有以下课程结构:

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

    public class Child : Parent
    {
        public int Property80;
    }

and a list of parent like this:和这样的父母名单:

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

I now want to make a new list of child that has all the data from parentList我现在想创建一个包含parentList所有数据的 child 的新列表

I know I can do this:我知道我可以这样做:

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

but my question is, is there a shorthand or one line way of doing this, to save me having to write a huge list of properties out?但我的问题是,是否有一种速记或单行方式来做到这一点,以免我不得不写出一大堆属性?

When you create the Parent list use Child class创建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 }
};

This is the equivalent of Parent p = new Child { Property1 = 1, Property2 = 2, Property3 = 3 }这相当于Parent p = new Child { Property1 = 1, Property2 = 2, Property3 = 3 }

Now you can cast it to Child and just add the missing properties in Select现在您可以将其转换为Child并在Select添加缺少的属性

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM