C#对象映射器

C#对象映射器

常规做法:

重载

public static implicit operator ClassB(ClassA v)
{
ClassBls = new ClassB();
ls.Id = v.Id;
}

直接复值

使用Mapster方式

像AutoMapper和Mapster就是解决这种问题的,而我为什么选择Mapster,主要还是Mapster性能更好!

基本映射之映射到新对象

 public void BasicMappingNewObject(SourceObjectTest sourceObject)
 {
    DestObjectTest destObject= sourceObject.Adapt<DestObjectTest>();
 }

基本映射之映射到现有对象

 public void BasicMappingExistObject(SourceObjectTest sourceObject)
 {
   DestObjectTest destObject = new DestObjectTest();
   destObject.Name = "李四";
   destObject.Age = new List<int> { 20 };
  destObject.Address = "中国XX省XX市XX县";
  destObject.Sex = "女";    
  destObject = sourceObject.Adapt(destObject);
 }

自定义映射

当我们的映射对象的属性与源对象的属性不一致时我们就可以使用!eg:SourceObjectTest的name属性和DifferentDestObjectTest的UserName是一个意思,只是创建Model类的时候取得名字不一样,这时候基本映射映射不了UserName字段,那我们就要使用自定义映射了!

一:直接在 TypeAdapterConfig 配置对象的映射关系

 public void BasicMappingExtend(SourceObjectTest sourceObject)
{
var config = new TypeAdapterConfig();
config.ForType<SourceObjectTest, DifferentDestObjectTest>()
            .Map(dest => dest.UserName, src => src.Name)
            .Map(dest => dest.Address, src => src.Name + src.Address);
var mapper = new Mapper(config);
 DifferentDestObjectTest differentDestObjectTest = mapper.Map<DifferentDestObjectTest>(sourceObject);
}

二:使用接口的方式

  public class DifferentDestObjectTestRegister : IRegister
    {
        public void Register(TypeAdapterConfig config)
        {
            config.ForType<SourceObjectTest, DifferentDestObjectTest>()
          .Map(dest => dest.UserName, src => src.Name)
          .Map(dest => dest.Address, src => src.Name + src.Address);
        }
    }
    
  public void BasicMappingExtend(SourceObjectTest sourceObject)
    {
            var config = new TypeAdapterConfig();
            config.Scan(Assembly.GetExecutingAssembly());
            var mapper = new Mapper(config);
            DifferentDestObjectTest differentDestObjectTest = mapper.Map<DifferentDestObjectTest>(sourceObject);
    }

三:使用映射配置

     public void MappingConfig(SourceObjectTest sourceObject)
        {
            TypeAdapterConfig<SourceObjectTest, DifferentDestObjectTest>
              .NewConfig()
              .Map(dest => dest.UserName,
                  src => src.Name);

        DifferentDestObjectTest differentDestObjectTest = TypeAdapter
        .Adapt<SourceObjectTest, DifferentDestObjectTest>(sourceObject);
        }

c#版BeanTool方式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Xml;

namespace SpotServer.Utils
{
    public class BeanUtils
    {
        /// <summary>
        /// 将IDictionary赋值给bean对象
        /// </summary>
        /// <param name="bean"></param>
        /// <param name="properties"></param>
        public static void Populate(object bean, IDictionary properties)
        {
            IDictionaryEnumerator ide = properties.GetEnumerator();
            while (ide.MoveNext())
            {
                SetProperty(bean, ide.Key.ToString(), ide.Value);
            }
        }
    /// <summary>
    /// 将IDictionary赋值给bean对象
    /// </summary>
    /// <param name="bean"></param>
    /// <param name="properties"></param>
    public static void Populate(object bean, IDictionary<string, object> properties)
    {
        foreach (string prop in properties.Keys)
        {
            SetProperty(bean, prop, properties[prop]);
        }
    }

    /// <summary>
    /// 将NameValueCollection赋值给bean对象
    /// </summary>
    /// <param name="bean"></param>
    /// <param name="properties"></param>
    public static void Populate(object bean, NameValueCollection properties)
    {
        string[] keys = properties.AllKeys;
        foreach (string key in keys)
        {
            SetProperty(bean, key, properties[key]);
        }
    }
     /// <summary>
    /// dr赋值给实例
    /// </summary>
    /// <param name="bean"></param>
    /// <param name="dr"></param>
    public static void Populate(object bean, DataRow dr)
    {
        IDictionary<string, object> dic = GetDictionary(dr);
        Populate(bean, dic);
    }

    /// <summary>
    /// dt得到实例
    /// </summary>
    /// <param name="bean"></param>
    /// <param name="dt"></param>
    /// <returns></returns>
    public static List<T> Populate<T>(T bean, DataTable dt)
    {
        List<T> l = new List<T>();

        List<IDictionary<string, object>> list = GetDictionary(dt);
        foreach (IDictionary dic in list)
        {
            T cloneBean = Activator.CreateInstance<T>();
            Populate(cloneBean, dic);
            l.Add(cloneBean);
        }

        return l;
    }

    /// <summary>
    /// dt得到实例
    /// </summary>
    /// <param name="bean"></param>
    /// <param name="dt"></param>
    /// <returns></returns>
    public static List<T> Populate<T>(T bean, XmlDocument dom, string beanTagName, DomPropertyType propType)
    {
        List<T> l = new List<T>();

        List<IDictionary<string, object>> list = GetDictionary(dom, beanTagName, propType);
        foreach (IDictionary dic in list)
        {
            T cloneBean = Activator.CreateInstance<T>();
            Populate(cloneBean, dic);
            l.Add(cloneBean);
        }

        return l;
    }

    /// <summary>
    /// 赋值bean
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="bean"></param>
    /// <returns></returns>
    public static T CloneBean<T>(T bean)
    {
        T o = Activator.CreateInstance<T>();
        CopyProperties(o, bean);

        return o;
    }

    public static void CopyProperties(object dest, object orig)
    {
        IDictionary cache = Describe(orig);
        Populate(dest, cache);
    }

    public static void CopyProperty(object bean, string name, object value)
    {
        SetProperty(bean, name, value);
    }

    public static IDictionary Describe(object bean)
    {
        Hashtable cache = new Hashtable();
        Type beantype = bean.GetType();
        PropertyInfo[] properties = beantype.GetProperties();
        foreach (PropertyInfo pi in properties)
        {
            string pname = pi.Name;
            object obj = pi.GetValue(bean, null);
            cache.Add(pname, obj);
        }

        return cache;
    }

    /// <summary>
    /// 获取对象的属性
    /// </summary>
    /// <param name="bean"></param>
    /// <param name="props"></param>
    /// <returns></returns>
    public static IDictionary<string, object> GetDictionaryProperties(object bean, string[] props)
    {
        IDictionary<string, object> dic = new Dictionary<string, object>();
        foreach (string prop in props)
        {
            object obj = GetProperty(bean, prop);
            dic.Add(prop, obj);
        }

        return dic;
    }

    /// <summary>
    /// 获取对象的所有属性
    /// </summary>
    /// <param name="bean"></param>
    /// <returns></returns>
    public static IDictionary<string, object> GetAllProperties(object bean)
    {
        IDictionary<string, object> dic = new Dictionary<string, object>();
        Type type = bean.GetType();
        PropertyInfo[] pinfos = type.GetProperties();
        foreach (PropertyInfo pi in pinfos)
        {
            dic.Add(pi.Name, pi.GetValue(bean, null));
        }

        return dic;
    }

    /// <summary>
    /// 获取对象指定的属性值
    /// </summary>
    /// <param name="bean">对象</param>
    /// <param name="name">属性名称</param>
    /// <returns></returns>
    public static object GetProperty(object bean, string name)
    {
        Type beantype = bean.GetType();
        PropertyInfo pi = beantype.GetProperty(name);
        return pi.GetValue(bean, null);
    }

    public static void SetProperty(object bean, string name, object value)
    {
        Type beantype = bean.GetType();
        PropertyInfo pi = beantype.GetProperty(name);
        object destValue = GetDestValue(pi, value);
        pi.SetValue(bean, destValue, null);
    }

    /// <summary>
    /// 获取值类型的默认值
    /// </summary>
    /// <returns></returns>
    private static object GetValueTypeDefaultValue(Type type)
    {
        object defValue;
        switch (type.FullName)
        {
            case "System.Boolean":
                defValue = false;
                break;
            case "System.Byte":
            case "System.SByte":
                defValue = Byte.MinValue;
                break;
            case "System.Int16":
            case "System.UInt16":
            case "System.Int32":
            case "System.UInt32":
            case "System.Int64":
            case "System.UInt64":
            case "System.Double":
            case "System.Single":
                defValue = Convert.ChangeType(0, type);
                break;
            case "System.Char":
                defValue = '0';
                break;
            case "System.DateTime":
                defValue = DateTime.MinValue;
                break;
            case "System.Decimal":
                defValue = Convert.ChangeType(0, type);
                break;
            default:
                defValue = 0;
                break;
        }

        return defValue;

    }

    /// <summary>
    /// 获取类型的最终值
    /// </summary>
    /// <param name="pi"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    private static object GetDestValue(PropertyInfo pi, object value)
    {
        Type propType = pi.PropertyType;
        if (propType.IsGenericType)
        {
            //泛型类型(包括可空类型)
            Type type = Nullable.GetUnderlyingType(propType);
            if (type != null)
            {
                if (value == DBNull.Value)
                {
                    value = null;
                }
                #region 作废该数据
                //if (type.IsValueType)
                //{
                //    //值类型
                //    if (value == DBNull.Value || value == null)
                //    {
                //        value = GetValueTypeDefaultValue(type);
                //    }
                //}
                //else
                //{
                //    //引用类型
                //    if (value == DBNull.Value)
                //    {
                //        value = null;
                //    }
                //}
                #endregion
            }

        }
        else
        {
            if (propType.IsValueType)
            {
                //值类型
                if (value == DBNull.Value || value == null)
                {
                    value = GetValueTypeDefaultValue(propType);
                }
            }
            else
            {
                //引用类型
                if (value == DBNull.Value)
                {
                    value = null;
                }
            }
        }

        return value;
    }
     /// <summary>
    /// 将DataRow转换成Hashtable
    /// </summary>
    /// <param name="row"></param>
    /// <returns></returns>
    public static IDictionary<string, object> GetDictionary(DataRow row)
    {
        IDictionary<string, object> dic = new Dictionary<string, object>();
        if (row != null)
        {
            foreach (DataColumn c in row.Table.Columns)
            {
                dic.Add(c.ColumnName, row[c]);
            }
        }

        return dic;
    }
    public static List<IDictionary<string, object>> GetDictionary(XmlDocument dom, string beanTagName, DomPropertyType propType)
    {
        List<IDictionary<string, object>> list = new List<IDictionary<string, object>>();
        switch (propType)
        {
            case DomPropertyType.ElementType:
                XmlNodeList nodes = dom.SelectNodes(string.Format(@"//" + beanTagName));
                foreach (XmlNode xn in nodes)
                {
                    IDictionary<string, object> dic = new Dictionary<string, object>();
                    XmlNodeList children = xn.ChildNodes;
                    foreach (XmlNode xnn in children)
                    {
                        dic.Add(xn.Name, xn.InnerText);
                    }
                    list.Add(dic);
                }
                break;
            case DomPropertyType.AttributeType:
                XmlNodeList ns = dom.SelectNodes(string.Format(@"//" + beanTagName));
                foreach (XmlNode xn in ns)
                {
                    IDictionary<string, object> dic = new Dictionary<string, object>();
                    XmlAttributeCollection attrs = xn.Attributes;
                    foreach (XmlAttribute attr in attrs)
                    {
                        dic.Add(attr.Name, attr.Value);
                    }
                    list.Add(dic);
                }
                break;
            default: break;
        }

        return list;
    }
     /// <summary>
    /// 将DataTable转换成List<Hashtable>
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    public static List<IDictionary<string, object>> GetDictionary(DataTable dt)
    {
        List<IDictionary<string, object>> list = new List<IDictionary<string, object>>();
        if (dt != null)
        {
            foreach (DataRow dr in dt.Rows)
            {
                list.Add(GetDictionary(dr));
            }
        }

        return list;
    }

    /// <summary>
    /// 将DataSet转成List
    /// </summary>
    /// <param name="ds"></param>
    /// <returns></returns>
    public static List<List<IDictionary<string, object>>> GetDictionary(DataSet ds)
    {
        List<List<IDictionary<string, object>>> list = new List<List<IDictionary<string, object>>>();
        if (ds != null && ds.Tables.Count > 0)
        {
            list.Add(GetDictionary(ds.Tables[0]));
        }

        return list;
    }
}

/// <summary>
/// 对象的值,是以节点的形式,还是以属性的形式
/// </summary>
public enum DomPropertyType
{
    ElementType = 0, AttributeType = 1
}
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值