Best way to create instance of child object from parent object

前端 未结 7 547
萌比男神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条回答
  •  -上瘾入骨i
    2020-12-11 00:38

    Seems natural for the base object to have constructor with parameters for its properties:

    public class MyObject 
    {
        public MyObject(prop1, prop2, ...)
        {
            this.Prop1 = prop1;
            this.Prop2 = prop2;
        }
    }
    

    So then, in your descendant object you can have:

    public MyObjectSearch(MyObject obj)
        :base(obj.Prop1, obj.Prop2)
    

    This reduces duplication related to assignments. You could use reflection to automatically copy all properties, but this way seems more readable.

    Note also, that if your classes have so much properties that you're thinking about automatizing of copying of the properties, then they are likely to violate the Single Responsibility Principle, and you should rather consider changing your design.

提交回复
热议问题