【问题标题】:Expression Tree of a Generic Action通用动作的表达式树
【发布时间】:2019-08-27 18:11:13
【问题描述】:

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

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

这可以实现吗?或者也许有一些更好/更简单的方法来做到这一点?

方法如下:

static GenericMethod<T>(Expression<Action<T>> doSomething) {  }

我只需要调用它,例如

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

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

【问题讨论】:

  • 表达式树应该做什么?只需调用Action&lt;T&gt;?或者Action&lt;T&gt; 在里面做什么?后者将非常困难,并且实际上需要反编译代码。也许无法编译但显示您在逻辑上想要做什么的代码会有所帮助。
  • @svick,感谢您的回复,我将尝试添加一些示例伪代码。干杯

标签: .net reflection expression-trees system.reflection


【解决方案1】:

看来你已经知道如何获取和调用泛型方法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());

那么,如何根据运行时Type 调用这个CreateWriteTypeExpression?与上述GenericMethod 相同,使用反射。

综合起来就是:

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 });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多