简体   繁体   中英

Copy properties from base class to derived class without manually mapping in C# with reflection

How can I copy properties from my base class instance to the derived class?

public class Base
{
    public string BaseProperty { get; set; }
}
public class House : Base
{
    public string HouseProp { get; set; }
}

I don't want to do this:

Base base = new Base() { BaseProperty = "Hello World" };
House house = new House();
house.BaseProperty = base.BaseProperty;
Base _base = new Base() { BaseProperty = "Hello World" };
House _house = new House(_base);


  public class Base
    {
        public string BaseProperty { get; set; }
    }
    public class House : Base
    {
        public House(Base _base)
        {
            foreach (PropertyInfo property in _base.GetType().GetProperties())
            {
                PropertyInfo propinfo = _base.GetType().GetProperty(property.Name);
                propinfo.SetValue(this, property.GetValue(_base, null), null);
            }

        }
        public string HouseProp { get; set; }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM