Best way to create instance of child object from parent object

前端 未结 7 541
萌比男神i
萌比男神i 2020-12-11 00:04

I\'m creating a child object from a parent object. So the scenario is that I have an object and a child object which adds a distance property for scenarios where I want to s

7条回答
  •  天涯浪人
    2020-12-11 00:34

    There are libraries to handle this; but if you just want a quick implementation in a few places, I would definitely go for a "copy constructor" as previously suggested.

    One interesting point not mentioned is that if an object is a subclass, then it can access the child's private variables from the within the parent!

    So, on the parent add a CloneIntoChild method. In my example:

    • Order is the parent class
    • OrderSnapshot is the child class
    • _bestPrice is a non-readonly private member on Order. But Order can set it for OrderSnapshot.

    Example:

    public OrderSnapshot CloneIntoChild()
    {
        OrderSnapshot sn = new OrderSnapshot()
        {
            _bestPrice = this._bestPrice,
            _closed = this._closed,
            _opened = this._opened,
            _state = this._state       
        };
        return sn;
    }
    

    NOTE: Readonly member variables MUST be set in the constructor, so you will have to use the child constructor to set these...

    Although I don't like "up-sizing" generally, I use this approach a lot for analytic snapshots...

提交回复
热议问题