Creating a cloned copy of subclass from baseclass

后端 未结 5 1704
鱼传尺愫
鱼传尺愫 2021-01-14 02:50

Consider this scenario:

public class Base
{
    public int i;
}

public class Sub : Base
{
    public void foo() { /* do stuff */}
}

And th

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-14 03:03

    You could use AutoMapper to avoid the tedium of writing the copy constructors.

    public class MyClass : MyBase
    {
        public MyClass(MyBase source)
        {
            Mapper.Map(source, this);
        }
    }
    

    and you need to run this once when your application starts up

    Mapper.CreateMap();
    

    You can download AutoMapper from https://github.com/AutoMapper/AutoMapper

提交回复
热议问题