如何将Linq Expression <Func <object,object,bool >>转换为Expression <Func <T1,T2,bool >>

时间:2019-11-26 17:06:10

标签: c# linq orm expression predicate

我试图将ORM的所有关联/联接存储在

列表中
public class OrmJoin{
  public Type Type1 { get; set;}
  public Type Type2 { get; set;}
  public bool IsRequired { get; set;}
  public Expression<Func<object, object, bool>> Predicate { get; set;}
}

然后我可以遍历此列表并将Predicate属性转换为 Expression<Func<T1,T2,bool>>通过使用typeof(Type1)typeof(Type2)以某种方式将前两个对象表达式参数转换为类型化参数?

1 个答案:

答案 0 :(得分:2)

这是您的操作方式:

public class OrmJoin
{
    // ...

    public Expression AsTyped()
    {
        var parameters = new[] { Type1, Type2 }
            .Select(Expression.Parameter)
            .ToArray();
        var castedParameters = parameters
            .Select(x => Expression.Convert(x, typeof(object)))
            .ToArray();
        var invocation = Expression.Invoke(Predicate, castedParameters);

        return Expression.Lambda(invocation, parameters);
    }
    public Expression<Func<T1, T2, bool>> AsTyped<T1, T2>() => (Expression<Func<T1, T2, bool>>)AsTyped();
}

void Main()
{
    var test = new OrmJoin { Type1 = typeof(string), Type2 = typeof(int), Predicate = (a,b) => Test(a,b) };
    var compiled = test.AsTyped<string, int>().Compile();

    Console.WriteLine(compiled.Invoke("asd", 312));
}
bool Test(object a, object b)
{
    Console.WriteLine(a);
    Console.WriteLine(b);
    return true;
}