编辑:好的,时间短但完整的程序。基本答案与以前相同:
- 使用Type.GetMethod查找“开放”通用方法
- 使用MakeGenericMethod使其通用
- 用调用来调用
这是一些示例代码。请注意,我已将查询表达式更改为点表示法-当您基本上只有一个where子句时,使用查询表达式毫无意义。
using System;using System.Linq;using System.Reflection;namespace Interfaces{ interface IFoo {} interface IBar {} interface IBaz {}}public class Test{ public static void CallMe<T>() { Console.WriteLine("typeof(T): {0}", typeof(T)); } static void Main() { MethodInfo method = typeof(Test).GetMethod("CallMe"); var types = typeof(Test).Assembly.GetTypes() .Where(t => t.Namespace == "Interfaces"); foreach (Type type in types) { MethodInfo genericMethod = method.MakeGenericMethod(type); genericMethod.Invoke(null, null); // No target, no arguments } }}原始答案
让我们忽略调用变量“接口”开始时的明显问题。
您必须通过反思来称呼它。泛型的重点是在 编译 时进行更多类型检查。您不知道编译时的类型是什么-因此必须使用泛型。
获取通用方法,并在其上调用MakeGenericMethod,然后调用它。
您的接口类型本身实际上是通用的吗?我问是因为您要在其上调用MakeGenericType,但没有传递任何类型参数…您是否要调用
Method<MyNamespace.Interface<string>>(); // (Or whatever instead of string)
要么
Method<MyNamespace.Interface>();
如果是后者,则只需要调用MakeGenericMethod-不需要MakeGenericType。


![使用仅在执行时已知的类型参数调用泛型方法[重复] 使用仅在执行时已知的类型参数调用泛型方法[重复]](http://www.mshxw.com/aiimages/31/416883.png)
