将属性从基类复制到派生类,而无需在C#中使用反射手动映射

时间:2018-10-22 06:34:36

标签: c#

如何将属性从基类实例复制到派生类?

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

我不想这样做:

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

1 个答案:

答案 0 :(得分:0)

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; }
    }