public class AutoMap
{
public List<string> BlackList = new List<string>();
//public void Map(object o1, object o2)
public void Map<K, T>(K o1, T o2)
{
for (int i = 0; i < BlackList.Count; i++)
{
BlackList[i] = BlackList[i].ToUpper();
}
//BlackList.ForEach(delegate(string s) { s = s.ToUpper(); });
//if (o1 == null || o2 == null)
// return;
//Type t1 = o1.GetType();
Type t1 = typeof(K);
IList<PropertyInfo> props1 = new List<PropertyInfo>(t1.GetProperties());
//Type t2 = o2.GetType();
Type t2 = typeof(T);
IList<PropertyInfo> props2 = new List<PropertyInfo>(t2.GetProperties());
for (int i = 0; i < props1.Count; i++)
{
object propValue1 = (o1 != null ? props1[i].GetValue(o1, null) : null);
string Name = props1[i].Name;
Type tt1 = props1[i].PropertyType;
for (int j = 0; j < props2.Count; j++)
{
if (!BlackList.Contains(props2[j].Name.ToUpper())
&& props2[j].Name.ToUpper() == Name.ToUpper())
{
object propValue2 = (o2 != null ? props2[j].GetValue(o2, null) : null);
Type tt2 = props2[j].PropertyType;
if (tt1.Equals(tt2))
{
if (o2!= null)
props2[j].SetValue(o2, propValue1, null);
}
else
{
if (tt1.IsClass && tt2.IsClass)
{
MethodInfo mi = this.GetType().GetMethod("Map").MakeGenericMethod(new Type[] { tt1, tt2 });
mi.Invoke(this, new object[] { propValue1, propValue2 });
props2[j].SetValue(o2, propValue2, null);
}
}
break;
}
}
}
}
}
你有什麼具體問題?這太寬泛了。你實際上是要求別人寫你的映射器。 –
你標記了你的文章'Automapper'。這是一個開源項目,已經完成了你所概述的內容。 –