c# - 字典初始值设定项的类型
问题描述
我有这个代码:
class Program
{
static void Main(string[] args)
{
var a = new Dictionary<string, int>()
{
{ "12", 12 },
{ "13", 13 },
};
}
static object Fifteen()
{
//return new object[] { "15", 15 };
return new {key = "15", value = 15};
}
}
如何编写Fifteen
以便可以将其添加到初始化程序?
我想要这个,编译:
var a = new Dictionary<string, int>()
{
{ "12", 12 },
{ "13", 13 },
Fifteen()
};
LE 编译错误是:error CS7036: There is no argument given that corresponds to the required formal parameter 'value' of 'Dictionary<string, int>.Add(string, int)'
解决方案
您需要更改您的方法Fifteen
,使其返回 aKeyValuePair
而不是object
它们被创建):
static KeyValuePair<string, int> Fifteen()
{
return new KeyValuePair<string, int>("15", 15);
}
然后你需要添加一个扩展方法,Dictionary
以便它有一个Add
接受一个KeyValuePair
而不是两个参数的方法:
public static void Add<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, KeyValuePair<TKey, TValue> pair)
{
dictionary.Add(pair.Key, pair.Value);
}
之后,您声明的代码编译并运行得很好。
推荐阅读
- html - 在 HTML 中添加边框
- html - 在 R distill 博客中通过 css 删除边界线
- python - .readframes(n) 中的 n 是什么意思?- 波Python
- django - Django auto_now 与 auto_now_add
- reactjs - 在 if 条件内调用方法 - React
- python - 如何在 AWS Elastic Beanstalk 中运行烧瓶 CLI 命令
- python - 无法使用 Selenium 访问 Amazon,请启用 Cookie
- angular - Angular invalid configuration(Webpack)
- opentracing - opentrace activeSpan 为空
- java - Java银行程序-如何从余额中扣除