AutoMapper映射使用,类数据交换

有时候需要批量进行类之间数据交换,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;
        }
    }
}

结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值