.net 泛型操作的表达式树

.net 泛型操作的表达式树,.net,reflection,expression-trees,system.reflection,.net,Reflection,Expression Trees,System.reflection,我需要用Action构建一个表达式树(如果我可以这样表述的话),但问题是T类型是在运行时通过反射确定的 我需要将此表达式作为参数传递给使用MethodInfo.InvokeAPI调用的通用方法。此方法的类型参数和上面提到的lambda应该匹配 这是可以实现的吗?或者可能有更好/更简单的方法 下面是该方法的外观: static GenericMethod<T>(Expression<Action<T>> doSomething) { } 静态泛型方法(表达式

我需要用
Action
构建一个表达式树(如果我可以这样表述的话),但问题是
T
类型是在运行时通过反射确定的

我需要将此表达式作为参数传递给使用
MethodInfo.Invoke
API调用的通用方法。此方法的类型参数和上面提到的lambda应该匹配

这是可以实现的吗?或者可能有更好/更简单的方法

下面是该方法的外观:

static GenericMethod<T>(Expression<Action<T>> doSomething) {  }
静态泛型方法(表达式doSomething){
我所需要的就是给它打电话,例如

Class.GenericMethod<string>(s => { Console.Write(s.GetType()); }
Class.GenericMethod(s=>{Console.Write(s.GetType());}

但我需要在运行时动态执行此操作。

您似乎已经知道如何获取和调用泛型方法
GenericMethod

var genericMethod = someType.GetMethod(nameof(GenericMethod), BindingFlags.NonPublic | BindingFlags.Static);
genericMethod.MakeGenericMethod(type).Invoke(null, …);
您可能已经知道如何创建一个方法,根据编译时
T
创建所需的表达式:

static Expression<Action<T>> CreateWriteTypeExpression<T>() =>
    s => Console.Write(s.GetType());

表达式树应该做什么?只需调用
操作
?或
操作
在其中所做的任何事情?后者将非常困难,并且实际上需要反编译代码。可能不编译但显示逻辑上想要做什么的代码会有所帮助。@svick,感谢您的回复,我将尝试添加一些示例代码,干杯
static Expression<Action<T>> CreateWriteTypeExpression<T>() =>
    s => Console.Write(s.GetType());

void CallGenericMethod(MethodInfo genericMethod, Type type)
{
    var writeTypeExpressionMethod = this.GetType()
        .GetMethod(nameof(CreateWriteTypeExpression), BindingFlags.NonPublic | BindingFlags.Static)
        .MakeGenericMethod(type);

    var writeTypeExpression = writeTypeExpressionMethod.Invoke(null, null);

    genericMethod.MakeGenericMethod(type).Invoke(null, new[] { writeTypeExpression });
}