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

如何通过int变量的值调用对应前缀名称的类方法

方案1:使用反射实现(适合方法数量少、调用频率低的场景)

using System.Reflection;

public class YourClass
{
    int i = 5;
    public void Method1(){}
    public void Method2(){}
    public void Method3(){}

    public void Method4()
    {
        // 拼接方法名
        string methodName = $"Method{i}";
        // 获取当前类的类型信息
        Type type = this.GetType();
        // 查找对应名称的公共无参实例方法
        MethodInfo method = type.GetMethod(methodName, BindingFlags.Public | BindingFlags.Instance);
        if (method != null)
        {
            // 调用方法,传入实例和参数(无参场景传null即可)
            method.Invoke(this, null);
        }
        else
        {
            // 处理方法不存在的情况,比如i超出1-3的有效范围
            throw new ArgumentException($"不存在名为{methodName}的方法");
        }
    }
}

注意:反射性能较差,且编译期不会检查方法是否存在,方法名、参数不匹配的问题只会在运行时报错

方案2:使用委托字典实现(更推荐,性能高、编译期可检查)

提前把方法和对应的i取值存入字典,调用时直接查表即可,比反射安全高效很多:

using System.Collections.Generic;

public class YourClass
{
    int i = 5;
    public void Method1(){}
    public void Method2(){}
    public void Method3(){}

    // 定义存储方法的字典,key是i的取值,value是对应无参方法的委托
    private Dictionary<int, Action> _methodMap;

    public YourClass()
    {
        // 构造函数里初始化映射关系
        _methodMap = new Dictionary<int, Action>()
        {
            {1, Method1},
            {2, Method2},
            {3, Method3}
        };
    }

    public void Method4()
    {
        if (_methodMap.TryGetValue(i, out var targetMethod))
        {
            targetMethod.Invoke();
        }
        else
        {
            throw new ArgumentException($"没有对应i={i}的方法");
        }
    }
}

该方案的优点是运行效率和直接调用方法几乎无差别,且编译期就能验证方法是否存在,不会出现运行时找不到方法的低级错误

内容的提问来源于stack exchange,提问作者Rednar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 08:54:02