Copying the contents of a base class from a derived class

后端 未结 10 1459
粉色の甜心
粉色の甜心 2021-01-01 17:19

I currently have a derived class and a base class. How can I make the base class of the derived class equal to a base class that I have? Will a shallow copy work?



        
10条回答
  •  臣服心动
    2021-01-01 17:53

    I realize that a couple of other answers may have touched on this solution, but I wanted to spell it out more completely.

    The solution I found was to populate the base class, then pass that base class into the constructor of the derived class. The constructor of the derived class populates its fields based on the base class.

    class Base
    {
        private string name; 
        public string Name { get; set; }
        private string address; 
        public string Address { get; set; }
    }
    
    class Derived:Base
    {
        Derived(Base toCopy)
        {
            this.Name = toCopy.Name;
            this.Address = toCopy.Address;
        }
    
        private string field; 
        public String field { get; set; }
    }
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                Base b = new Base();
                b.Address = "Iliff";
                b.Name = "somename"; 
    
                //You are now passing the base class into the constructor of the derived class.
                Derived d = new Derived(b);
    
    
            }
        }
    }
    

提交回复
热议问题