class SelectItem { public string Item { get; set; } } class SelectList { public int ID { get; set; } public string Name { get; set; } public SelectItem Item { get; set; } } class SelectListDto : SelectList { } static Func<SelectList, SelectListDto> Test() { var entityType = typeof(SelectList); var selectListDtoType = typeof(SelectListDto); var selectItemType = typeof(SelectItem); var entityIDProperty = entityType.GetProperty("ID"); var entityNameProperty = entityType.GetProperty("Name"); var entityItemProperty = entityType.GetProperty("Item"); var entityItemItemProperty = entityItemProperty.PropertyType.GetProperty("Item"); var selectListDtoIDProperty = selectListDtoType.GetProperty("ID"); var selectListDtoNameProperty = selectListDtoType.GetProperty("Name"); var selectListDtoItemProperty = selectListDtoType.GetProperty("Item"); var selectListDtoItemItemProperty = selectListDtoItemProperty.PropertyType.GetProperty("Item"); var parameterExpression = Expression.Parameter(entityType); var newInstantiationExpression = Expression.New(selectListDtoType); var idMemberExpression = Expression.Property(parameterExpression, entityIDProperty); var nameMemberExpression = Expression.Property(parameterExpression, entityNameProperty); var itemMemberExpression = Expression.Property(parameterExpression, entityItemProperty); var innerObjNew = Expression.New(selectItemType); var nestedItemMemberExpression = Expression.Property(itemMemberExpression, entityItemItemProperty); var idBinding = Expression.Bind(selectListDtoIDProperty, idMemberExpression); var nameBinding = Expression.Bind(selectListDtoNameProperty, nameMemberExpression); var nestedItemBinding = Expression.Bind(entityItemItemProperty, nestedItemMemberExpression); var nestedInit = Expression.MemberInit(innerObjNew, nestedItemBinding); var nestedBinding = Expression.Bind(entityItemProperty, nestedInit); var bindings = new List<MemberAssignment>() { idBinding, nameBinding, nestedBinding}; var memberInitExpression = Expression.MemberInit(newInstantiationExpression, bindings); var lambda = Expression.Lambda<Func<SelectList, SelectListDto>>(memberInitExpression, parameterExpression); return lambda.Compile(); }
参考地址:
https://stackoverflow.com/a/51764873
https://stackoverflow.com/a/31465017/7712266
https://docs.microsoft.com/zh-cn/dotnet/csharp/expression-trees