数据对象的强转换

来源:互联网 发布:淘宝情趣丝袜女模特 编辑:程序博客网 时间:2024/06/05 02:17

因为在使用接口的时候,数据库的生成的model 是不对外的,那么,就需要创建专门对外的接口模型。

一:若属性相同

1、基于返回对象的转换:

/// <summary>/// 将一个对象的属性值转移到另外一个对象里(相同值)/// </summary>/// <typeparam name="TDestination"></typeparam>/// <param name="source"></param>/// <returns></returns>public static TDestination ConvertPropertiesToModel<TDestination>(this object source)    where TDestination : new(){    try    {        TDestination retModel = new TDestination();     //实例化被转换对象        Type sourceType = source.GetType();        List<PropertyInfo> sourcePropertyList = sourceType.GetProperties().ToList(); //获取数据源类型的所有属性        Type destinationType = typeof(TDestination);        List<PropertyInfo> destinationPropertyList = destinationType.GetProperties().ToList(); //获取目标类型的所有属性        foreach (PropertyInfo propertyInfo in destinationPropertyList) //遍历目标类型的所有属性        {            if (sourcePropertyList.Where(x => x.Name.Equals(propertyInfo.Name)).Count() > 0)            //拥有相同的属性            {                PropertyInfo sourcePropertyInfo = sourcePropertyList.Where(x => x.Name.Equals(propertyInfo.Name)).FirstOrDefault();                object value = sourcePropertyInfo.GetValue(source);//获取数据源里面该属性的值                propertyInfo.SetValue(retModel, value);            }        }        return retModel;    }    catch (Exception)    {        return new TDestination();    }}

2、基于源数据对象和待转换对象的转换:

/// <summary>/// 将一个对象的属性值转移到另外一个对象里(相同值)/// </summary>/// <typeparam name="TResource"></typeparam>/// <typeparam name="TDestination"></typeparam>/// <param name="source"></param>/// <returns></returns>public static TDestination ConvertPropertiesToModel<TResource, TDestination>(this object source)    where TDestination : new(){    try    {        TDestination retModel = new TDestination();     //实例化被转换对象        Type sourceType = typeof(TResource);        List<PropertyInfo> sourcePropertyList = sourceType.GetProperties().ToList(); //获取数据源类型的所有属性        Type destinationType = typeof(TDestination);        List<PropertyInfo> destinationPropertyList = destinationType.GetProperties().ToList(); //获取目标类型的所有属性        foreach (PropertyInfo propertyInfo in destinationPropertyList) //遍历目标类型的所有属性        {            if (sourcePropertyList.Where(x => x.Name.Equals(propertyInfo.Name)).Count() > 0)            //拥有相同的属性            {                PropertyInfo sourcePropertyInfo = sourcePropertyList.Where(x => x.Name.Equals(propertyInfo.Name)).FirstOrDefault();                object value = sourcePropertyInfo.GetValue(source);//获取数据源里面该属性的值                propertyInfo.SetValue(retModel, value);            }        }        return retModel;    }    catch (Exception)    {        return new TDestination();    }}

3、将一个对象列表的属性值转移到另外一个对象列表里

 /// <summary> /// 将一个对象列表的属性值转移到另外一个对象列表里(相同键) /// </summary> /// <typeparam name="TDestination"></typeparam> /// <param name="source"></param> /// <returns></returns> public static List<TDestination> ConvertPropertiesToModelList<TResource, TDestination>(this List<TResource> source)     where TDestination : new() {     List<TDestination> retList = new List<TDestination>();     source.ForEach(x =>     {         retList.Add(x.ConvertPropertiesToModel<TResource, TDestination>());     });     return retList; }

测试

public class MyClass1{    public int Id { get; set; }    public string Name { get; set; }    public string Rmk { get; set; }    public override string ToString()    {        return string.Format("Id:{0},Name:{1},Rmk:{2}", Id, Name, Rmk);    }} public class MyClass2 {     public int Id { get; set; }     public string Name { get; set; }     public int Age { get; set; }     public override string ToString()     {         return string.Format("Id:{0},Name:{1},Age:{2}", Id, Name, Age);     } }static void Main(string[] args){    MyClass1 myClass1 = new MyClass1()    {        Id = 12,        Name = "张三",        Rmk = "备注"    };    Stopwatch stopwatch1 = new Stopwatch();    stopwatch1.Start();    for (int i = 0; i < 500000; i++)    {        MyClass2 myClass2 = myClass1.ConvertPropertiesToModel<MyClass2>();    }    stopwatch1.Stop();    Console.WriteLine("stopwatch1:" + stopwatch1.ElapsedMilliseconds);    Stopwatch stopwatch2 = new Stopwatch();    stopwatch2.Start();    for (int i = 0; i < 500000; i++)    {        MyClass2 myClass2 = myClass1.ConvertPropertiesToModel<MyClass1, MyClass2>();    }    stopwatch2.Stop();    Console.WriteLine("stopwatch2:" + stopwatch2.ElapsedMilliseconds);    Console.ReadLine();}结果:stopwatch1:2290stopwatch2:1806

小结:推荐使用第二个,减少一次装箱拆箱,性能会有一定的提升

二:若字母相同

/// <summary>/// 将一个对象的属性值转移到另外一个对象里(相同值,但是格式不一样)/// </summary>/// <typeparam name="TDestination"></typeparam>/// <param name="source"></param>/// <returns></returns>public static TDestination ConvertPropertiesToModelWithOutFormat<TDestination>(this object source, params string[] replaceValues)    where TDestination : new(){    try    {        TDestination retModel = new TDestination();     //实例化被转换对象        Type sourceType = source.GetType();        List<PropertyInfo> sourcePropertyList = sourceType.GetProperties().ToList(); //获取数据源类型的所有属性        Type destinationType = typeof(TDestination);        List<PropertyInfo> destinationPropertyList = destinationType.GetProperties().ToList(); //获取目标类型的所有属性        foreach (PropertyInfo propertyInfo in destinationPropertyList) //遍历目标类型的所有属性        {            if (sourcePropertyList.Where(x => x.Name.GetKeyWithoutFormat(replaceValues).Equals(propertyInfo.Name.GetKeyWithoutFormat(replaceValues))).Count() > 0)            //拥有相同的属性            {                PropertyInfo sourcePropertyInfo = sourcePropertyList                    .Where(x => x.Name.GetKeyWithoutFormat(replaceValues).Equals(propertyInfo.Name.GetKeyWithoutFormat(replaceValues))).FirstOrDefault();                object value = sourcePropertyInfo.GetValue(source);//获取数据源里面该属性的值                propertyInfo.SetValue(retModel, value);            }        }        return retModel;    }    catch (Exception)    {        return new TDestination();    }}/// <summary>/// 替换字符串/// </summary>/// <param name="key"></param>/// <param name="replaceValues"></param>/// <returns></returns>private static string GetKeyWithoutFormat(this string key, string[] replaceValues){    if(replaceValues != null)    {        foreach(string replaceValue in replaceValues)        {            key = key.Replace(replaceValue, "");        }    }    return key.ToLower();}

数据模型

public class MyClass3{    public string MY_ID { get; set; }    public int MY_AGE { get; set; }    public string MY_RMK { get; set; }}public class MyClass4{    public string MyId { get; set; }    public int MyAge { get; set; }    public string MyRmk { get; set; }}

测试代码

MyClass3 myClass3 = new MyClass3(){     MY_ID = "1212",     MY_AGE = 15,     MY_RMK ="1212" }; var myClass4 = myClass3.ConvertPropertiesToModelWithOutFormat<MyClass4>("_");

结果:全部赋值成功

三:若属性不同的,需通过mapping关联

这种情况需要通过mapping对应的Name来取值,赋值。代码略

原创粉丝点击