如何使用反射的GetMethod获取带ref关键字的方法?
解决反射查找带ref参数方法的问题
哦,这个问题我之前也碰到过!问题出在你处理ref参数的方式上——反射里查找带ref/out参数的方法时,不能直接用typeof(int),得用它的引用类型版本。
问题根源
ref int本质上是传递参数的引用,在反射中对应的Type对象不是普通的typeof(int),而是需要通过MakeByRefType()方法生成的特殊类型。你当前的代码用普通的int类型去匹配,自然找不到对应的方法。
修改后的代码
把参数类型数组改成使用MakeByRefType()的版本,就能正确找到方法了:
[Button(nameof(Method))] public bool whatever; private void Test(ref int i) { Debug.Log("Works"); } private void Method() { // 关键修改:用MakeByRefType()创建ref int对应的Type Type[] types = { typeof(int).MakeByRefType() }; MethodInfo methodInfo = GetType().GetMethod( nameof(Test), BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static, null, types, null ); Debug.Log(methodInfo); // 现在应该能输出方法信息了 }
额外说明
- 对于
out参数,处理方式和ref完全一致,同样需要用MakeByRefType()生成对应的Type对象。 - 你的
BindingFlags设置是正确的,已经覆盖了私有实例方法的查找范围,不需要调整。
内容的提问来源于stack exchange,提问作者Christoph Wolf
相关产品推荐
相关产品推荐

