如何将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
相关产品推荐
相关产品推荐

