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

如何将KeyValuePair传入接收ICollection<KeyValuePair<string,string>>的方法?

解决方案

你可以通过创建实现了ICollection<KeyValuePair<string, string>>接口的集合实例来传递目标键值对,以下是几种常用的写法:

方法1:用List初始化

_restActions.ExecutePostRequest(resource, body, new List<KeyValuePair<string, string>>
{
    new KeyValuePair<string, string>("auth", "local")
});

方法2:用数组传递(数组默认实现ICollection接口)

_restActions.ExecutePostRequest(resource, body, new[]
{
    new KeyValuePair<string, string>("auth", "local")
});

方法3:用HashSet初始化

_restActions.ExecutePostRequest(resource, body, new HashSet<KeyValuePair<string, string>>
{
    new KeyValuePair<string, string>("auth", "local")
});

如果你的项目使用C# 7.0及以上版本,还能用到更简洁的值元组语法(编译器会自动转换为KeyValuePair):

_restActions.ExecutePostRequest(resource, body, new List<(string Key, string Value)>
{
    ("auth", "local")
});

核心逻辑是:只要传入的对象实现了ICollection<KeyValuePair<string, string>>接口,方法就能正常接收,上面几种方式都合法,选你觉得最简洁的即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 12:42:38