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

C#如何实现类似Python按函数名查找并调用对应函数的功能

C# 实现字符串标识到函数的映射调用

C#实现该逻辑的核心思路和Python完全一致:用字典存储「字符串标识」和「函数引用」的映射关系,运行时根据输入取出对应函数传入参数调用即可。C#中用委托作为函数引用的承载类型,对于签名统一的函数,直接用内置泛型委托就能快速实现。

场景1:所有待映射函数签名完全一致

比如示例里的两个Python函数,都是接收两个整数参数、无返回值的形式,直接用内置的Action<参数类型1, 参数类型2>委托即可(如果函数有返回值,就用Func<参数类型1, 参数类型2, 返回值类型>),对应实现代码和Python逻辑完全对齐:

using System;
using System.Collections.Generic;

class Testa
{
    // 对应Python的funca
    static void FuncA(int a = 0, int b = 1)
    {
        Console.WriteLine($"aaa {a} {b}");
    }

    // 对应Python的funcb
    static void FuncB(int a = 2, int b = 3)
    {
        Console.WriteLine($"bbb {a} {b}");
    }

    // 对应Python的func_dict,key为输入标识,value为匹配签名的委托
    static Dictionary<string, Action<int, int>> funcDict = new Dictionary<string, Action<int, int>>()
    {
        {"a", FuncA},
        {"b", FuncB}
    };

    static void Main()
    {
        string inp = Console.ReadLine()?.Trim();
        // 尝试取值,对应Python的dict.get()判空逻辑,避免key不存在报错
        if (funcDict.TryGetValue(inp, out var targetFunc))
        {
            targetFunc(1, 2);
        }
    }
}

场景2:待映射函数签名不统一

如果要存储的函数参数个数、类型、返回值不统一,可以定义一个入参为object[]、返回值为object的通用委托,把不同签名的方法用Lambda包一层适配即可:

static Dictionary<string, Func<object[], object>> generalFuncDict = new Dictionary<string, Func<object[], object>>()
{
    {"a", args => {
        FuncA((int)args[0], (int)args[1]);
        return null;
    }},
    {"other", args => {
        // 适配仅需要1个字符串参数的方法
        return AnotherFunc((string)args[0]);
    }}
};

// 调用时统一传object数组参数
if (generalFuncDict.TryGetValue(inp, out var targetFunc))
{
    targetFunc(new object[]{1, 2});
}

补充说明

  • 如果要映射的是实例方法而非静态方法,字典赋值时直接绑定实例即可,比如{"a", instanceOfTesta.FuncA},用法和静态方法没有区别。
  • 优先用TryGetValue方法做字典取值,和Python中dict.get()的判空逻辑一致,避免key不存在时抛出异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 12:09:22