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

C#如何调用存储为字符串的带参数静态方法

解决通过字典调用带参静态方法的问题

需求说明

通过字典关联文件夹名称与其他类的静态方法名,遍历文件夹下的文件时,根据当前文件夹名称调用匹配的静态方法,并传入文件路径作为参数。

原代码问题

原主类代码存在方法类型获取错误、Invoke参数传递错误、文件夹名称获取效率低等问题,导致无法正确调用目标静态方法。

原主类代码

foreach (string folder in folders)
{
    foreach (string file in Directory.EnumerateFiles(folder))
    {
        //switch (folder)
        //{
        //}
        foreach(var a in GetDictionaryToFunction())
        {
            string nameFolder = folder.Split('\\')[folder.Split('\\').Count() - 1];
            if (a.Key == nameFolder)
            {
                //And here I want to use the specified method with file path as param.
                Type thisType = this.GetType();
                MethodInfo theMethod = thisType.GetMethod(a.Value);// +"("+ file + ")");
                theMethod.Invoke(theMethod, null);
            }
        }
    }
}

目标静态方法所在类(File类)

class File
{
    public static void ReadPayments(string filePath)
    {
        string[] rows = Reader.ReadCsv(filePath);
        if (rows.Count() == 0) return;

        listPlatnosci.Clear();
        string fileName = Path.GetFileName(filePath);

        foreach (string row in rows)
        {
            TransformRow(row, fileName);
        }
    }
}

修正后的代码

主类修正代码

// 字典示例:键为文件夹名,值为对应静态方法名
Dictionary<string, string> folderMethodMap = new Dictionary<string, string>
{
    {"Payments", "ReadPayments"},
    // 可添加更多文件夹与方法的映射
};

foreach (string folder in folders)
{
    // 优化文件夹名称获取:兼容不同系统路径分隔符
    string folderName = Path.GetFileName(folder);
    
    // 直接从字典匹配方法名,避免无效遍历
    if (folderMethodMap.TryGetValue(folderName, out string methodName))
    {
        foreach (string file in Directory.EnumerateFiles(folder))
        {
            // 获取目标静态方法所在类的Type
            Type fileType = typeof(File);
            // 指定参数类型,精准匹配带参方法
            MethodInfo targetMethod = fileType.GetMethod(
                methodName, 
                new[] { typeof(string) }
            );
            
            if (targetMethod != null)
            {
                // 调用静态方法:第一个参数为null(无需实例),第二个参数传文件路径
                targetMethod.Invoke(null, new object[] { file });
            }
        }
    }
}

关键修改点

  • 修正方法类型获取:目标静态方法属于File类,因此使用typeof(File)而非this.GetType()(后者获取当前主类的类型)
  • 正确传递Invoke参数:静态方法调用时Invoke第一个参数为null;第二个参数为方法参数数组,传入new object[] { file }传递文件路径
  • 优化字典查找逻辑:用TryGetValue直接匹配文件夹名,避免遍历整个字典,提升效率
  • 优化文件夹名称获取:用Path.GetFileName(folder)替代两次Split操作,兼容多系统路径格式且更高效
  • 明确方法参数类型:调用GetMethod时指定参数类型,确保匹配到正确的带参方法重载

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 21:10:28