.Net 对象映射(简单映射) 实现类似automapper

2 篇文章 0 订阅
2 篇文章 0 订阅
  1. 首先创建一个EntityMapper类
public class EntityMapper
{
    /// <summary>
    ///  类似于aotumapper得功能 对象
    /// </summary>
    /// <typeparam name="T">需要转换得类型</typeparam>
    /// <typeparam name="V">参数类型</typeparam>
    /// <returns></returns>
    public static T ConvertEntity<T, V>(V v) where T : class
        where V : class
    {
        try
        {
            //转换类型
            var t_type = typeof(T);
            //声明T类型得实例
            var t_entity = Activator.CreateInstance<T>();
            //参数类型
            var v_type = typeof(V);
            //获取需要转换得property
            var property_t = t_type.GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
            //获取参数类型得property
            var property_v = v_type.GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
            foreach (var _v in property_v)
            {
                //获取v得属性名
                var v_propertyName = _v.Name;
                //获取属性名对应得值
                var value = _v.GetValue(v);

                foreach (var t in property_t)
                {
                    var t_propertyName = t.Name;
                    //判断当前属性得特性是否存在
                    if (t.IsDefined(typeof(CustomPropertyAttribute), true))
                    {
                        //存在时找特性中与Name一样得

                        //获取T当前属性得自定义特性
                        var t_attribute = t.GetCustomAttributes(typeof(CustomPropertyAttribute), true);
                        foreach (CustomPropertyAttribute item in t_attribute)
                        {

                            var v_name = property_v.FirstOrDefault(p => p.Name == item.Name);
                            if (v_name is not null)
                            {
                                t.SetValue(t_entity, v_name.GetValue(v));
                            }
                        }
                    }
                    else
                    {
                        //不存在直接找一样名字得
                        //如果两个属性名相同进行映射
                        if (v_propertyName.ToLower() == t_propertyName.ToLower())
                        {
                            if (t_entity != null)
                            {
                                t.SetValue(t_entity, value);
                                break;
                            }
                        }
                    }
                }
            }
            return t_entity;
        }
        catch (Exception ex)
        {
            throw new IndexOutOfRangeException(ex.Message);
        }
       
       
    }


    /// <summary>
    /// 类似于aotumapper得功能 集合
    /// </summary>
    /// <typeparam name="T">需要转换得类型</typeparam>
    /// <typeparam name="V">参数类型</typeparam>
    /// <param name="v_list"></param>
    /// <returns></returns>
    public static List<T> ConvertEntity<T, V>(List<V> v_list) where T : class where V : class
    {
        try
        {
            //声明一个T集合
            var t_list = new List<T>();
            if (v_list.Count == 0 || v_list is null)
            {
                return t_list;
            }
            //v得type
            var v_type = typeof(V);
            var v_property = v_type.GetProperties();
            获取T得type
            var t_type = typeof(T);
            var t_property = t_type.GetProperties();

            foreach (var v_item in v_list)
            {
                //声明一个T对象
                var t_entity = Activator.CreateInstance<T>();
                foreach (var t_p in t_property)
                {
                    if (t_p.IsDefined(typeof(CustomPropertyAttribute), true))
                    {
                        //获取T当前属性得自定义特性
                        var t_attribute = t_p.GetCustomAttributes(typeof(CustomPropertyAttribute), true);
                        foreach (CustomPropertyAttribute item in t_attribute)
                        {
                            var v_name = typeof(V).GetProperties().FirstOrDefault(p => p.Name.ToLower() == item.Name.ToLower());
                            if (v_name is not null)
                            {
                                t_p.SetValue(t_entity, v_name.GetValue(v_item));
                            }
                        }
                    }
                    else
                    {
                        var temp = v_property.FirstOrDefault(p => p.Name == t_p.Name);
                        if (temp is not null)
                        {
                            t_p.SetValue(t_entity, temp.GetValue(v_item));
                        }
                    }
                }

                t_list.Add(t_entity);
            }
            return t_list;
        }
        catch (Exception ex)
        {
            throw new IndexOutOfRangeException(ex.Message);
        }
        

    }
}
  1. 创建一个自定义特性CustomPropertyAttribute
/// <summary>
    /// 字段 不运行重复使用  只能用在属性上
    /// </summary>
    [AttributeUsage(AttributeTargets.Property,AllowMultiple = false)]
    public class CustomPropertyAttribute: Attribute
    {
        public CustomPropertyAttribute(string name)
        {
            Name = name;
        }

        public string Name { get; set; }
    }
  1. 创建一个Student类
public class Student
{

    public int Id { get; set; }

  
    public string Name { get; set; }
}
  1. 创建一个Teacher类
public class Teacher
    {
		/// <summary>
        /// 指定被转换得名字
        /// </summary>
        [CustomProperty("Id")]
        public int sd { get; set; }

      
        public string Name { get; set; }
    }
  1. 调用
var stus = new List<Student>() { new Student { Id = 1, Name = "锤锤" } , new Student { Id = 2, Name = "王大锤" } };
var stu = new Student {Id=1,Name = "123" };
var a =  EntityMapper.ConvertEntity<Teacher, Student>(stus);
var b = EntityMapper.ConvertEntity<Teacher, Student>(stu);
Console.ReadLine();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
在 .NET 中,可以使用AutoMapper库来实现automap映射两个list。具体实现如下: 首先,需要安装AutoMapper库,可以使用以下NuGet命令安装: ``` Install-Package AutoMapper ``` 然后,创建一个映射配置类,用于指定list1和list2的映射关系。例如: ```csharp public class MappingProfile : Profile { public MappingProfile() { CreateMap<int, string>(); } } ``` 接着,在程序中使用以下代码进行映射: ```csharp var config = new MapperConfiguration(cfg => cfg.AddProfile<MappingProfile>()); var mapper = new Mapper(config); var list1 = new List<int> { 1, 2, 3 }; var list2 = mapper.Map<List<int>, List<string>>(list1); foreach (var item in list2) { Console.WriteLine(item); } ``` 在上面的代码中,首先创建一个MapperConfiguration对象,并指定映射配置类。然后,创建一个Mapper对象,并使用Map方法将list1映射为list2。最后,遍历list2并输出结果。 输出结果为: ``` null null null ``` 这是因为我们只指定了int到string的映射关系,但没有指定具体的映射规则。因此,需要在MappingProfile中添加具体的映射规则。例如: ```csharp public class MappingProfile : Profile { public MappingProfile() { CreateMap<int, string>().ConvertUsing(s => (s * 2).ToString()); } } ``` 这里的ConvertUsing方法用于指定具体的映射规则。在这个例子中,我们将int类型的值乘以2,并将结果转化为string类型。然后,再次运行程序,输出结果为: ``` 2 4 6 ``` 这样就完成了automap映射两个list的操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值