我可以使用强类型反射找到具有泛型参数的方法吗?

Can I find a method with generic parameters using strongly typed reflection?

这是我尝试使用类型参数调用现有泛型方法的尝试。 '强类型反射'可能不是一个合适的术语,但它基本上意味着在不使用名称字符串的情况下查找和调用反射方法。

public class TestClass
{
    public static void Test(Type type)
    {
        InvokeTestMethodWithType(type);
    }

    private void Test<T>() { ... }

    private static void InvokeTestMethodWithType(Type type)
    {
        // This doesn't compile! - can I find Test<> using this approach?
        Expression<Func<TestClass, Action>> ex = x => x.Test<>;

        // invoke it
        ((MethodCallExpression)ex.Body).Method.MakeGenericMethod(type).Invoke(new TestClass(), null);
    }
}

示例调用最终会调用私有 Test()。

TestClass.Test(typeof(Foo))

如您所见,我正在为表达式苦苦思索,不完全确定它是否可以以这种方式执行。

我是否必须像这样在表达式中虚拟调用操作 post

x => x.Test<object>()

我使用的技巧很简单:传递一个伪造的泛型类型参数:

Expression<Func<TestClass, WhateverTestReturns>> ex = x => x.Test<string>();

// invoke it
((MethodCallExpression)ex.Body)
  .Method
  .GetGenericMethodDefinition()
  .MakeGenericMethod(type)
  .Invoke(new TestClass(), null);

方法调用表达式将包含 Test<string>() 的方法信息,但您可以轻松地使用 GetGenericMethodDefinition 删除通用参数,然后使用 MakeGenericMethod 放置不同的参数回到原位。

在这种情况下,您甚至不需要使用 Expression - 只需将 TestClass.Test<string> 转换为委托,您就会得到 Method 属性 为您提供相同的方法信息。