问题
Imagine that we have three classes like this:
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; }
}
I have an anonymous Expression like this:
x => new
{
x.Id,
Sub = new
{
x.Sub.Id,
ColSubs = x.Sub.ColSubs.Select(u=> new {
u.Id
}).ToList()
}
}
I need to transform it to a non anonymous Expression like this:
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()
}
}
Thanks to @IvanStoev's answer for this question: Variable 'x.Sub' of type 'SubType' referenced from scope '' but it is not defined error I am able to transform the simple Expressions, but when I add x.Sub.ColSubs.Select(...)
I get the following error:
System.ArgumentException: Argument types do not match
回答1:
Following is a code you need to add to the recursive Transform
method which handles exactly that scenario, i.e. detect Select
method, transform the selector
argument, modify the TResult
generic type argument of the Select
and call it with the new selector
, and finally call ToList
in case the destination is not 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);
}
来源:https://stackoverflow.com/questions/55809842/argument-types-do-not-match-transforming-anonymous-expressionfunct-u-to-non