copy chosen properties to object of other type

前端 未结 2 869
旧时难觅i
旧时难觅i 2021-01-28 06:06

I need to copy properties of one object to another, both objects can be of different type, can have properties of same name. These property can also be of complex type.

相关标签:
2条回答
  • 2021-01-28 06:21

    You can try using the AutoMapper as @Kevin mentioned. If you still need a custom method, you can try this. Note: It copies the value to the property in the target object itself and does not look for the property as in the expression tree.

    private static void Assign<T1, T2>(T1 T1Obj, T2 T2Obj, Expression<Func<T1, object>> memberLamda)
    {
        var memberSelectorExpression = memberLamda.Body as MemberExpression;
    
        if (memberSelectorExpression != null)
        {
            var sourceProperty = memberSelectorExpression.Member as PropertyInfo;
    
            if (sourceProperty != null)
            {
                var targetProperty = T2Obj.GetType().GetProperty(sourceProperty.Name);
    
                if (targetProperty != null)
                {
                    targetProperty.SetValue(T2Obj, GetValue(T1Obj, memberSelectorExpression));
                }
            }
        }
    }
    
    public static object GetValue<T>(T source, MemberExpression expr)
    {
        var sourceProperty = expr.Member as PropertyInfo;
    
        var nextExpression = expr.Expression as MemberExpression;
    
        if (nextExpression == null)
        {
            return sourceProperty.GetValue(source);
        }
    
        var sourcePart = GetValue(source, nextExpression);
        return sourceProperty.GetValue(sourcePart);
    }
    
    0 讨论(0)
  • 2021-01-28 06:24

    Use AutoMapper and ignore the members you don't want to map.

    config.CreateMap<Person, Employee>()
        .ForMember(d => d.Name, o => o.MapFrom(s => s.FullName))
        .ForMember(d => d.Age, o => o.Ignore());
    
    0 讨论(0)
提交回复
热议问题