相关疑难解决方法(0)

我可以为Dictionary <TKey,TValue>条目使用集合初始值设定项吗?

我想为下一段代码使用集合初始值设定项:

public Dictionary<int, string> GetNames()
{
    Dictionary<int, string> names = new Dictionary<int, string>();
    names.Add(1, "Adam");
    names.Add(2, "Bart");
    names.Add(3, "Charlie");
    return names;
}
Run Code Online (Sandbox Code Playgroud)

通常它应该是这样的:

return new Dictionary<int, string>
{ 
   1, "Adam",
   2, "Bart"
   ...
Run Code Online (Sandbox Code Playgroud)

但是这个的正确语法是什么?

.net c# generics collections c#-3.0

94
推荐指数
5
解决办法
4万
查看次数

标签 统计

.net ×1

c# ×1

c#-3.0 ×1

collections ×1

generics ×1