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

C#如何向方法传递<string,object>参数集并遍历提取各参数键名和值

C# 匿名类型参数遍历实现方案

参数类型选择建议

  • 不推荐使用dynamic作为参数类型:dynamic会关闭编译期类型检查,增加不必要的运行时解析开销,且该场景下不需要用到动态分发能力,属于不必要的使用。
  • 更优的参数类型选择有两种:
    1. 优先选择Dictionary<string, object>:类型明确,原生支持遍历,性能最优,调用代码仅需少量调整,示例如下:
    UpdateCustomer(customerId, new Dictionary<string, object> { ["Area"] = 23, ["CustomerName"] = "Bob Smith" });
    
    1. 必须保留匿名对象调用写法时,选择object作为参数类型:不需要用到dynamic的能力,用普通object即可满足需求。

报错原因说明

你编写的foreach代码报错的核心原因是:匿名类型是C#编译器自动生成的普通CLR类,仅包含你定义的属性成员,没有实现IEnumerable接口,本身不支持被foreach遍历,即使转为dynamic类型也不会改变这个本质。

功能实现代码

方案1:参数为Dictionary<string, object>(最推荐)

无需反射,直接遍历即可:

public void UpdateCustomer(int customerId, Dictionary<string, object> parameters)
{
    foreach (var kvp in parameters)
    {
        string paramName = kvp.Key;
        object paramValue = kvp.Value;
        
        if (paramValue is string strVal)
        {
            // 处理字符串类型参数逻辑
        }
        else if (paramValue is int intVal)
        {
            // 处理整数类型参数逻辑
        }
        else 
        {
            throw new InvalidOperationException($"不支持的参数类型:{paramValue.GetType().Name}");
        }
    }
}

方案2:入参为匿名对象的情况

通过反射读取对象的属性列表实现遍历:

using System.Reflection;

public void UpdateCustomer(int customerId, object parameters)
{
    // 反射获取对象所有公共实例属性
    PropertyInfo[] properties = parameters.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
    foreach (var prop in properties)
    {
        string paramName = prop.Name;
        object paramValue = prop.GetValue(parameters);
        
        // 类型判断处理逻辑和方案1一致
        if (paramValue is string strVal)
        {
            // 处理字符串类型参数逻辑
        }
        else if (paramValue is int intVal)
        {
            // 处理整数类型参数逻辑
        }
        else 
        {
            throw new InvalidOperationException($"不支持的参数类型:{paramValue.GetType().Name}");
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 00:27:03