对象互拷贝ValueInjecter 分类: .NET 2014-05-22 21:34 878人阅读 评论(0) 收藏

假设有A、B两个类,他们的成员完全相同,在给对象A设完值后,想让对象B也像A一样,有设置过的值,此时可用ValueInjecter来解决。


代码:

using System;
using System.Collections.Generic;
using System.Text;

using Omu.ValueInjecter;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            A a = new A() { a="a", b="1", c=2 };
            B b = new B();
            b.InjectFrom(a);
        }
    }

    class A
    {
        public string a { get; set; }
        public string b { get; set; }
        public int c { get; set; }
    }

    class B
    {
        public string a { get; set; }
        public string b { get; set; }
        public int c { get; set; }
    }
}


其中Omu.ValueInjecter.dll为第三方dll文件,下载地址为:http://valueinjecter.codeplex.com/

与本帖相同demo的地址为:http://valueinjecter.codeplex.com/documentation (网页的最下方有相关demo链接,其中最后一个关于DAL操作)


此dll在本论坛下载地址:http://download.csdn.net/detail/config_man/7387141


PS:在实际开发中,还没遇到过此需求,发此贴是因为在同一个群的一个网友问了相关问题,群里另一位网友贡献的。在此仅作知识的积累。

上面的代码中,请注意拷贝的顺序,别写成a.InjectFrom(b),这样是拷贝不了的。


原文地址:https://www.cnblogs.com/configman/p/4657543.html