我有一个静态方法,它有两个参数,一个是包含所有信息的源对象,另一个是我想要传输所有值的目标对象。
问题是该类有嵌套类,我不知道如何将它添加到dest
对象。
我感谢所有帮助。
调用方法如下所示:
Automapper(annonsDto, new Annons(){
Model = new Model()
{Company = new Company()},
User = new Users()});
private static Object Automapper(Object source, Object dest)
{
PropertyInfo[] sourcePropertyInfos = source.GetType().GetProperties();
Array.Sort(sourcePropertyInfos, delegate(PropertyInfo propertyInfo1, PropertyInfo propertyInfo2)
{
return propertyInfo1.Name.CompareTo(propertyInfo2.Name);
});
foreach (PropertyInfo sourcePropertyInfo in sourcePropertyInfos)
{
if (sourcePropertyInfo.PropertyType.IsClass)
{
if (sourcePropertyInfo.PropertyType.FullName.ToLower().Contains("xXxXx"))
{
var nestedClass = sourcePropertyInfo.GetValue(source, null);
Automapper(nestedClass, dest);
continue;
}
}
dest = TransferPropValue(sourcePropertyInfo.Name, source, dest);
}
return dest;
}
private static Object TransferPropValue(String targetName, Object sourceObj, Object destObj)
{
if (sourceObj == null)
{
return null;
}
Type destType = destObj.GetType();
PropertyInfo destInfo = destType.GetProperty(targetName);
Type sourceType = sourceObj.GetType();
PropertyInfo sourceInfo = sourceType.GetProperty(targetName);
if (sourceInfo == null) { return null; }
try
{
var sourceValue = sourceInfo.GetValue(sourceObj, null);
destInfo.SetValue(destObj, sourceValue, null);
}
catch (Exception) { }
return destObj;
}