Copying the contents of a base class from a derived class

后端 未结 10 1461
粉色の甜心
粉色の甜心 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:54

    Create a copy constructor for the base class, in doing so you'll also need to create a parameterless one as well as by adding the copy constructor the default constructor will no longer be generated by the compiler. Then in the derived class call the base class's copy constructor.

    public class Base
    {
        public int Name { get; set; }
        public string Address { get; set; }
    
        public Base()
        { }
    
        public Base(Base toCopy)
        {
            this.Name = toCopy.Name;
            this.Address = toCopy.Address;
        }
    }
    
    public class Derived : Base
    {
        public String Field { get; set; }
    
        public Derived(Base toCopy)
            : base (toCopy)
        { }
    
        // if desired you'll need a parameterless constructor here too
        // so you can instantiate Derived w/o needing an instance of Base
        public Derived()
        { }
    }
    

提交回复
热议问题