有时候需要批量进行类之间数据交换,AutoMapper是一个功能dll库函数,需要下载,使用举例如下,vs2019+控制台窗体程序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
namespace AutoMapTest
{
class Program
{
static void Main(string[] args)
{
MonKey MonkeyBig = new MonKey("大猴子","大香蕉");
MonKey MonkeySmall = new MonKey("小猴子", "小香蕉");
Rabbt RabbtBig = new Rabbt("大兔子", "大萝卜");
Rabbt RabbtSmall = new Rabbt("小兔子", "小萝卜");
MapperMonkey = new MapperConfiguration(set =>
{
set.CreateMap<MonKey, MonKey>();
set.CreateMap<Rabbt, MonKey>();// Rabbt的参数赋值给MonKey,改变monkey
set.CreateMap<MonKey, Rabbt>();// MonKey的参数赋值给Rabbt,改变rabbit
}).CreateMapper();
Console.WriteLine("MonkeyBig的参数传递给MonkeySmall");
MonKeyAToMonKeyB(MonkeyBig, MonkeySmall);
Console.WriteLine("MonkeyBig的信息");
Console.WriteLine(MonkeyBig.name+"!"+ MonkeyBig.food);
Console.WriteLine("MonkeySmall的信息");
Console.WriteLine(MonkeySmall.name + "!" + MonkeySmall.food);
Console.WriteLine("RabbtSmall的参数传递给MonkeyBig");
RabbtToMonKey(MonkeyBig, RabbtSmall);
Console.WriteLine("MonkeyBig");
Console.WriteLine(MonkeyBig.name + "!" + MonkeyBig.food);
Console.WriteLine("RabbtSmall");
Console.WriteLine(RabbtSmall.Named + "!" + RabbtSmall.food);
Console.WriteLine("由于猴子和兔子的参数名字不同,只传递出了food参数");
Console.ReadKey();
}
static IMapper MapperMonkey;
public static void MonKeyAToMonKeyB(MonKey MonKeyA, MonKey MonKeyB)
{
MapperMonkey.Map<MonKey, MonKey>(MonKeyA, MonKeyB);
}
public static void RabbtToMonKey(MonKey monkey, Rabbt rabbit)
{
MapperMonkey.Map<Rabbt, MonKey>(rabbit, monkey);
}
}
class MonKey
{
public String name = "猴子";
public String food = "香蕉";
public MonKey(string name="",string food="")
{
this.name = name;
this.food = food;
}
}
class Rabbt
{
public String Named = "兔子";
public String food = "胡萝卜";
public Rabbt(string name = "", string food = "")
{
this.Named = name;
this.food = food;
}
}
}
结果: