using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks; namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
People p = new People() { Age = 28, name = new Name() { FirstName = "zheng", LastName = "zhiqiang" } };
PeopleDto pDto = new PeopleDto();
pDto = AutoMapping<People, PeopleDto>.Convert(p, pDto);
Console.WriteLine(string.Format("{0} {1} {2}", pDto.Age, pDto.FirstName, pDto.LastName));
Console.Read();
}
}
/// <summary>
///
/// </summary>
/// <typeparam name="T1">entity</typeparam>
/// <typeparam name="T2">dto</typeparam>
public static class AutoMapping<T1, T2>
where T1 : new()
where T2 : new()
{
public static T2 Convert(T1 t1, T2 t2)
{
var dtoPiList = t2.GetType().GetProperties().Where(x => x.PropertyType.IsPublic).ToList();
string name;
object value;
for (int i = 0; i < dtoPiList.Count(); i++)
{
name = dtoPiList[i].Name;
value = GetPropertyValue(t1, name);
if (null == value) continue;
dtoPiList[i].SetValue(t2, value, null);
}
return t2;
}
private static object GetPropertyValue(object t1, string name)
{
Type t = t1.GetType();
PropertyInfo[] pis = t.GetProperties();
//查找当前对象是否包含需要转换的属性
var piTemp = pis.Where(x => x.Name == name).FirstOrDefault();
//不存在递归查询
if (piTemp == null)
{
foreach (PropertyInfo pi in pis)
{
object obj1 = pi.GetValue(t1, null);
object obj2 = GetPropertyValue(obj1, name);
if (obj2 != null) { return obj2; }
}
}
else
{
//判断是否忽略标记
var cAttr = piTemp.GetCustomAttributes();
foreach (var attr in cAttr)
{
var tempAttr = attr as AutoMappingAttributes;
if (tempAttr.Ignore) { return null; }
}
//存在直接返回
return piTemp.GetValue(t1, null);
}
return null;
}
}
public class AutoMappingAttributes : Attribute
{
public bool Ignore { get; set; }
}
public class Name
{
public string FirstName { get; set; }
[AutoMappingAttributes(Ignore = true)]
public string LastName { get; set; }
} public class People
{
public int Age { get; set; }
public Name name { get; set; } }
public class NameDto
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class PeopleDto
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
} }