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

C# 我可以使用强类型反射找到具有泛型参数的方法吗?,c#,generics,reflection,C#,Generics,Reflection,下面是我用类型参数调用现有泛型方法的尝试。”“强类型反射”可能不是一个合适的术语,但它基本上意味着在不使用名称字符串的情况下查找和调用反射的方法 public class TestClass { public static void Test(Type type) { InvokeTestMethodWithType(type); } private void Test<T>() { ... } private static

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

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);
    }
}
正如您所看到的,我正在努力处理这个表达式,并不完全确定它是否可以以这种方式执行

我必须像这样在表达式中伪调用操作吗

x=>x.Test()

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

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

// invoke it
((MethodCallExpression)ex.Body)
  .Method
  .GetGenericMethodDefinition()
  .MakeGenericMethod(type)
  .Invoke(new TestClass(), null);
表达式ex=x=>x.Test(); //调用它 ((MethodCallExpression)ex.Body) .方法 .GetGenericMethodDefinition() .MakeGenericMethod(类型) .Invoke(新TestClass(),null); 然后,方法调用表达式将包含
Test()
的方法信息,但您可以轻松地使用
GetGenericMethodDefinition
删除泛型参数,然后使用
MakeGenericMethod
将另一个参数放回原处


在这种情况下,您甚至不需要使用
表达式
,只需将
TestClass.Test
转换为委托,您将拥有一个
方法
属性,该属性将为您提供相同的方法信息。

如果您使
InvokeTestMethodWithType
期望泛型类型会怎么样?@NielsFilter如果可以,我会这样做,但它只能在运行时从类型映射中得知。+1非常棒,感谢您对
GetGenericMethodDefinition()的支持
并使用委托。重新编写以使用“代理”并像符咒一样工作。
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);