1

我有一个静态方法,它有两个参数,一个是包含所有信息的源对象,另一个是我想要将所有值传输到的目标对象。

问题是该类具有嵌套类,我不知道如何将其添加到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;
    }
4

0 回答 0