【发布时间】:2013-07-30 21:40:23
【问题描述】:
假设我有一个像这样的类,包含一个带有 out 参数的泛型方法:
public class C
{
public static void M<T>(IEnumerable<T> sequence, out T result)
{
Console.WriteLine("Test");
result = default(T);
}
}
通过阅读其他几个问题(How to use reflection to call generic Method? 和 Reflection on a static overloaded method using an out parameter)的答案,我认为我可以通过反射调用该方法,如下所示:
// get the method
var types = new[] { typeof(IEnumerable<int>), typeof(int).MakeByRefType() };
MethodInfo mi = typeof(C).GetMethod(
"M", BindingFlags.Static, Type.DefaultBinder, types, null);
// convert it to a generic method
MethodInfo generic = mi.MakeGenericMethod(new[] { typeof(int) });
// call it
var parameters = new object[] { new[] { 1 }, null };
generic.Invoke(null, parameters);
但是mi 将返回 null。我尝试在types 数组中使用object 而不是int,但这也不起作用。
如何在调用MakeGenericMethod之前为泛型方法指定类型(out 参数所需)?
【问题讨论】:
-
你的真实班级有
M的重载吗?如果没有,您可以在不需要指定参数类型的情况下使用GetMethod变体。但这并不能回答您提出的问题。 -
在这种特定情况下,我将能够通过不指定任何类型而只使用名称来解决它,正如@SLaks 所建议的那样。我仍然想知道指定模板类型数组的语法是什么,或者它是否不可能。
-
我出错的地方是我认为必须传递类型数组才能使用
out或ref参数。事实并非如此...只要您通过某种方式获得了正确的MethodInfo,您就可以将参数数组传递给它,它会设置值。
标签: c# generics reflection