Best way to create instance of child object from parent object

前端 未结 7 543
萌比男神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:57

    There is no easy way to do this, unfortunately. As you said, you would either have to use reflection, or create a "Clone" method that would generate a new child object using a parent object as input, like so:

    public class MyObjectSearch : MyObject {
    
        // Other code
    
        public static MyObjectSearch CloneFromMyObject(MyObject obj)
        {
            var newObj = new MyObjectSearch();
    
            // Copy properties here
            obj.Prop1 = newObj.Prop1;
    
            return newObj;
        }
    }
    

    No matter what, you're either going to end up writing reflection code (which is slow), or writing each property out by hand. It all depends on whether or not you want maintainability (reflection) or speed (manual property copy).

    0 讨论(0)
提交回复
热议问题