Copying the contents of a base class from a derived class

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

    You will have to manually copy the fields of the Base instance to the new Derived instance.

    A common way of doing this is by offering a copy constructor:

    public Derived(Base other)
    {
        if (other == null) {
            throw new ArgumentNullException("other");
        }
    
        this.name = other.name;
        this.address = other.address;
    }
    

    One more note about your code:

    private string field; 
    public string Field { get; set; }
    

    This does not make much sense (same for the other properties).

    public string Field { get; set; } means that a private field will automatically be created by the compiler. Your field field will never be used at all.

    Either just write public string Field { get; set; }, as the private field will be created automatically. Or declare the Field property in a way so that your private field will be used:

    private string field;
    
    public string Field {
        get {
            return field;
        }
        set {
            field = value;
        }
    }
    

提交回复
热议问题