想象一下,我们有三个这样的类:
public class ParentType {
private ParentType() {}
public int Id { get; protected set; }
public SubType Sub { get; protected set; }
}
public class SubType{
private SubType(){}
public int Id { get; protected set; }
public ICollection<ColSubType> ColSubs{get; protected set;}
}
public class ColSubType{
private ColSubType(){}
public int Id { get; protected set; }
public SubType SubType { get; set; }
}
我有一个像这样的匿名表达式:
x => new
{
x.Id,
Sub = new
{
x.Sub.Id,
ColSubs = x.Sub.ColSubs.Select(u=> new {
u.Id
}).ToList()
}
}
我需要将它转换为非匿名表达式,如下所示:
x => new ParentType()
{
Id = x.Id,
Sub = new SubType()
{
Id = x.Sub.Id,
ColSubs = x.Sub.ColSubs.Select(u=> new ColSubs(){
Id = u.Id
}).ToList()
}
}
感谢@ IvanStoev对这个问题的回答:Variable 'x.Sub' of type 'SubType' referenced from scope '' but it is not defined error我能够转换简单的表达式,但是当我添加x.Sub.ColSubs.Select(...)
时,我收到以下错误:
System.ArgumentException:参数类型不匹配
下面是你需要添加到递归Transform
方法的代码,它正好处理那个场景,即检测Select
方法,转换selector
参数,修改TResult
的Select
泛型类型参数并用新的selector
调用它,最后调用ToList
如果目的地不是IEnumerable<T>
:
if (source.Type != type && source is MethodCallExpression call && call.Method.IsStatic
&& call.Method.DeclaringType == typeof(Enumerable) && call.Method.Name == nameof(Enumerable.Select))
{
var sourceEnumerable = call.Arguments[0];
var sourceSelector = (LambdaExpression)call.Arguments[1];
var sourceElementType = sourceSelector.Parameters[0].Type;
var targetElementType = type.GetGenericArguments()[0];
var targetSelector = Expression.Lambda(
Transform(sourceSelector.Body, targetElementType),
sourceSelector.Parameters);
var targetMethod = call.Method.GetGenericMethodDefinition()
.MakeGenericMethod(sourceElementType, targetElementType);
var result = Expression.Call(targetMethod, sourceEnumerable, targetSelector);
if (type.IsAssignableFrom(result.Type)) return result;
return Expression.Call(
typeof(Enumerable), nameof(Enumerable.ToList), new[] { targetElementType },
result);
}