【问题标题】:new Dictionary { [person] = person } which version of c# supports this syntax?new Dictionary { [person] = person } 哪个版本的 c# 支持这种语法?
【发布时间】:2022-03-12 04:06:49
【问题描述】:

是否可以使用以下语法在 C# 中实例化 Dictonary

Person person = new Person();
var dictionary = new Dictionary { [person] = person };

如果是,那么什么版本的 C# 支持它?

目前我正在运行 Visual Studio 2019 社区版,但它不支持这种语法。

【问题讨论】:

  • 也许Dictionary<int, Person> dictionary = new() { [1] = person }; see also
  • Dictionary<string, Person> dictionary = new() { {"person", person} };var dictionary = new Dictionary<string, Person> { {"person", person} };?

标签: c# dictionary


【解决方案1】:

你应该把你的代码写成这样:

Person person = new Person();
var dictionary = new Dictionary<string,person>() { "person" , person };

你甚至可以这样写

Person person = new Person();
var dictionary = new Dictionary<string,person>() { "person" , new person {....}};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-20
    • 2016-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-04
    相关资源
    最近更新 更多