Best way to create instance of child object from parent object

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

    You can use reflection to copy properties.

    public class ChildClass : ParentClass
    {
    
    
        public ChildClass(ParentClass ch)
        {
            foreach (var prop in ch.GetType().GetProperties())
            {
                this.GetType().GetProperty(prop.Name).SetValue(this, prop.GetValue(ch, null), null);
            }
        }
    }
    

提交回复
热议问题