一直以來都是使用JsonConvert套件來做物件的複製,但是最近遇到了點困難,導致有些物件是不能這樣用的

參考了小章大的文章:連結網址1  連結網址2  受益良多

先安裝AutoMapper套件

先增兩個Class

  public class Person1
        {
            public string Name { set; get; }
            public int Age { set; get; }
        }

  public class Person2
        {
            public string Name { set; get; }
            public int Age1 { set; get; }
        }


 private static void Main(string[] args)
        {
            Person1 one = new Person1();
            one.Name = "Mars";
            one.Age = 18;

            //var mapperconfig = new MapperConfiguration(o => o.CreateMap<Person1, Person2>());
            //mapperconfig.AssertConfigurationIsValid();//證驗應對,如失敗會出現錯誤
            //var map = mapperconfig.CreateMapper();

            var mapperconfig = new MapperConfiguration(o => o.CreateMap<Person1, Person2>()).CreateMapper();
            //Person2 two = new Person2();
            //map.Map(one, two);
            var two = mapperconfig.Map<Person2>(one);

            Console.WriteLine($"Name:{one.Name},Age:{one.Age}");
            Console.WriteLine($"Name:{two.Name},Age1:{two.Age1}");
            //改變狀態
            two.Age1 = 100;
            two.Name = "Bill";
            Console.WriteLine($"Name:{one.Name},Age:{one.Age}");
            Console.WriteLine($"Name:{two.Name},Age1:{two.Age1}");
            Console.ReadLine();
        }

arrow
arrow
    文章標籤
    AutoMapper C#
    全站熱搜

    軒軒的爸媽 發表在 痞客邦 留言(0) 人氣()