cast the Parent object to Child object in C#

前端 未结 7 1242
春和景丽
春和景丽 2020-12-01 07:00

Hi i want to cast the Parent object to Child object in C#

public class Parent
{
    public string FirstName {get; set;}
    public string LastName {get; set;         


        
相关标签:
7条回答
  • 2020-12-01 07:31

    If I understand your "I just want to fill them automatically" comment correctly, you want to create a new Child object that's populated with the values of the Parent, with default values for the new properties. Best way to do that is to create a constructor that copies the values:

    public class Parent
    {
       public string FirstName {get; set;}
        public string LastName {get; set;}
        public string City {get; set;}
    }
    
    public class Child : Parent
    {
        public string PhoneNumber {get; set;}
        public string MobileNumber {get; set;}
    
        public Child (Parent parentToCopy)
        {
            this.FirstName = parentToCopy.FirstName;
            this.LastName = parentToCopy.LastName;
            this.City = parentToCopy.City;
    
            this.PhoneNumber = string.Empty; // Or any other default.
            this.MobileNumber = string.Empty;
        } 
    }
    

    Now you can use LINQ, like the answers above, to create a Child out of each Parent:

    List<Child> lstChild = lstParent.Select(parent => new Child(parent)).ToList();
    

    Note that this is very similar to @daryal's answer, but wraps the parent-to-child copying logic inside the constructor, rather than having it outside in the new Child() call.

    0 讨论(0)
提交回复
热议问题