对象复制方法在.NET:自动映射器,排出映射器,隐式操作,属性复制映射器、属性、对象、操作

2023-09-02 23:43:52 作者:6.油炸小可爱

如果有人知道在.NET这样做的更多的方式,也是你有什么意见有关办法?哪种方法你选择,为什么?

If some one knows any more ways of doing this in .NET and also what is your opinions about that approaches? Which approach you choose and why?

下面是对象拷贝.NET不同方式的测试。

Here is the tests of different ways of object copy in .NET.

测试与此相关的原帖:http://stackoverflow.com/questions/531505/how-to-copy-value-from-class-x-to-class-y-with-the-same-property-name-in-c

所以,在这里,你可以运行它自己的:

So, here it is, you can run it yourself:

static void Main(string[] args)
    {
        Student _student = new Student();
        _student.Id = 1;
        _student.Name = "Timmmmmmmmaaaahhhh";
        _student.Courses = new List<int>();
        _student.Courses.Add(101);
        _student.Courses.Add(121);

        Stopwatch sw = new Stopwatch();

        Mapper.CreateMap<Student, StudentDTO>();            

        StartTest(sw, "Auto Mapper");

        for (int i = 0; i < 1000000; i++)
        {
            StudentDTO dto = Mapper.Map<Student, StudentDTO>(_student);
        }

        StopTest(sw);

        StartTest(sw, "Implicit Operator");

        for (int i = 0; i < 1000000; i++)
        {
            StudentDTO itemT = _student;
        }

        StopTest(sw);

        StartTest(sw, "Property Copy");

        for (int i = 0; i < 1000000; i++)
        {

            StudentDTO itemT = new StudentDTO
            {
                Id = _student.Id,
                Name = _student.Name,
            };

            itemT.Courses = new List<int>();
            foreach (var course in _student.Courses)
            {
                itemT.Courses.Add(course);
            }
        }

        StopTest(sw);

        StartTest(sw, "Emit Mapper");

        ObjectsMapper<Student, StudentDTO> emitMapper = ObjectMapperManager.DefaultInstance.GetMapper<Student, StudentDTO>();

        for (int i = 0; i < 1000000; i++)
        {
            StudentDTO itemT = emitMapper.Map(_student);
        }

        StopTest(sw);
    }

我的电脑上测试的结果:

Tests results on my PC:

测试自动映射:22322毫秒

Test Auto Mapper:22322 ms

测试隐运营商:310毫秒

Test Implicit Operator:310 ms

测试属性复制:250毫秒

Test Property Copy:250 ms

测试的Emit映射器:281毫秒

Test Emit Mapper:281 ms

您可以从这里发射和经销商-mappers:

You can get emit and auto -mappers from here:

HTTP://emitmapper.$c$cplex.com/

HTTP://automapper.$c$cplex.com/

推荐答案

另外,也可以使用T4生成类,将产生财产副本code。

It is also possible to use T4 to generate classes that will generate property copy code.

好:运行速度,因为它是可能的 不好:T4中的编码 丑:使构建脚本,可编译这一切一气呵成

Good: runs as fast as it is possible Bad: "coding" in T4 Ugly: Making build scripts that allow you to compile it all in one go