一直以來都是使用JsonConvert套件來做物件的複製,但是最近遇到了點困難,導致有些物件是不能這樣用的
先安裝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();
}