cast the Parent object to Child object in C#

前端 未结 7 1264
春和景丽
春和景丽 2020-12-01 07:00

Hi i want to cast the Parent object to Child object in C#

public class Parent
{
    public string FirstName {get; set;}
    public string LastName {get; set;         


        
7条回答
  •  隐瞒了意图╮
    2020-12-01 07:15

    I do so (this is just an example):

    using System.Reflection;
    
    public class DefaultObject
    {
        ...
    }
    
    public class ExtendedObject : DefaultObject
    {
        ....
        public DefaultObject Parent { get; set; }
    
        public ExtendedObject() {}
        public ExtendedObject(DefaultObject parent)
        {
            Parent = parent;
    
            foreach (PropertyInfo prop in parent.GetType().GetProperties())
                GetType().GetProperty(prop.Name).SetValue(this, prop.GetValue(parent, null), null);
        }
    }
    

    Using:

    DefaultObject default = new DefaultObject { /* propery initialization */ };
    ExtendedObject extended = new ExtendedObject(default); // now all properties of extended are initialized by values of default properties.
    MessageBox.Show(extended.Parent.ToString()); // now you can get reference to parent object
    

提交回复
热议问题