You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用反射的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:03:05