通过反射获取方法失败

时间:2011-08-25 17:36:53

标签: c# reflection overloading

我有以下方法由 G1

决定
public static void Get(int pname, out int @params)

我试图通过以下方式使用反射来获取它:

MethodInfo mGetMethod = typeof(Gl).GetMethod("Get",
                                             BindingFlags.Public|BindingFlags.Static,
                                             null, 
                                             new Type[] 
                                             { 
                                                 typeof(Int32), 
                                                 typeof(Int32) 
                                             }, 
                                             null);

但我没有成功。为什么呢?

是因为 out 关键字吗?

4 个答案:

答案 0 :(得分:7)

使用typeof(Int32).MakeByRefType()作为第二个参数。即:

MethodInfo mGetMethod = typeof(Gl).GetMethod("Get", bindingFlags.Public|BindingFlags.Static, null, new Type[] { typeof(Int32), typeof(Int32).MakeByRefType() }, null);

答案 1 :(得分:1)

如果你需要为方法指定特定的重载,那么肯定会使用@Isaac Overacker所说的内容。否则只是不要指定参数:

MethodInfo mGetMethod = typeof(Gl).GetMethod("Get", BindingFlags.Public | BindingFlags.Static);

答案 2 :(得分:1)

out关键字通过引用传递参数,这可能是你的问题。您需要将其标记为引用类型,因为C#允许您使用byValue和byReference参数重载方法。

答案 3 :(得分:0)

如何尝试这样的事情:

MethodInfo method = this.GetType().GetMethod("Get");
if (method != null)
{
    method.Invoke(this, new object[] { "Arg1", "Arg2", "Arg3" });
}