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

如何通过Reflection.ParameterInfo获取ByRef类型的基础类型

反射处理ref参数的基础类型获取与比较方案
  • 获取ref参数的基础类型:当ParameterInfo.ParameterType.IsByRef返回true时,调用ParameterType.GetElementType()方法就能拿到该引用参数对应的原始基础类型(比如ref int对应的System.Int32)。
  • 正确的程序化比较写法:
    先判断参数是否为引用传递,再对比其拆解后的基础类型,代码示例:
    if (paramInfo.ParameterType.IsByRef && paramInfo.ParameterType.GetElementType() == typeof(int))
    {
        // 匹配到ref int类型的参数,执行对应逻辑
    }
    
  • 关键说明:System.Int32&是CLR层面的引用类型标识,C#语法里不允许直接用typeof(System.Int32&)或typeof(ref int)来声明这种类型,所以必须通过GetElementType()来拆解获取底层的原始类型。

举个实际使用的例子,针对你提到的DoStuff(ref int count)方法:

// 假设YourClass是包含DoStuff方法的类
MethodInfo method = typeof(YourClass).GetMethod("DoStuff");
foreach (ParameterInfo param in method.GetParameters())
{
    if (param.ParameterType.IsByRef)
    {
        Type baseType = param.ParameterType.GetElementType();
        Console.WriteLine($"该ref参数的基础类型:{baseType.FullName}"); // 输出 System.Int32
        if (baseType == typeof(int))
        {
            Console.WriteLine("成功匹配到ref int类型的参数");
        }
    }
}

内容的提问来源于stack exchange,提问作者NⵙⵙB

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 17:12:07