cast the Parent object to Child object in C#

前端 未结 7 1240
春和景丽
春和景丽 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:04

    Another way to approach this solution is to have the Parent control the copy logic and Child will pass the copy source into the base constructor.

    e.g. iterating on Avner's solution

    public class Parent
    {
        public string FirstName {get; set;}
        public string LastName {get; set;}
        public string City {get; set;}
    
        public Parent()
        {
        }
    
        public Parent(Parent copyFrom)
        {
            this.FirstName = copyFrom.FirstName;
            this.LastName = copyFrom.LastName;
            this.City = copyFrom.City;
        }
    }
    
    public class Child : Parent
    {
        public string PhoneNumber {get; set;}
        public string MobileNumber {get; set;}
    
        public Child (Parent parentToCopy) : base(parentToCopy)
        {
        } 
    }
    

提交回复
热议问题