【问题标题】:Can C# 9.0 records support data structures like dictionaries and lists?C# 9.0 记录能否支持字典和列表等数据结构?
【发布时间】:2020-11-14 15:01:43
【问题描述】:

我已经看到了 C# 9.0 中新记录功能的几个示例。即,能够更新单个属性以创建新的不可变记录。我很想知道with 语法是否允许我将新条目插入到字典之类的东西中,从而创建一个新的不可变字典以及构成记录的所有兄弟属性。

例如,我可以这样做吗?

public record Person
{
    public string Name;
}
 
public record Car
{
    public string Model;
    public Dictionary<string, Person> Riders;
}

var car = new Car 
{
    Model = "Delorean",
    Riders = ("driver", new Person { Name = "Doc Brown" })
};

var newCar = car with
{ 
    Riders with ("passenger1", new Person { Name = "Marty McFly" })
};

【问题讨论】:

  • FWIW 我认为这是一个有效的问题,但答案是“不是真的”。您也许可以考虑不可变集合 API,其中 Add 等是函数而不是方法(意思是:它们返回不同的集合,它们不会更改现有集合)
  • 你能解释一下你上面使用的类似元组的语法吗?它对我来说似乎不是有效的 C#,即使在 C# 9 中也是如此。我错过了什么吗?

标签: c# .net data-structures immutability


【解决方案1】:

正如this comment 中所述,您肯定不能这样做,因为with 仅适用于记录类型。但无论如何,你的意思也不完全清楚。 Dictionary&lt;TKey, TValue&gt; 类从一开始就不是一成不变的,所以 with 似乎没有必要。您希望上面建议的语法能做什么?

如果您的意思是替换字典内容,您可以使用当前的with 语法轻松地做到这一点:

var newCar = car with
{
    Riders = new Dictionary<string, Person> { { "passenger1", new Person { Name = "Marty McFly" } } }
};

如果您的意思是添加到现有的字典内容,但使用一个新的实例,这不是很优雅,但仍然很容易,对我来说似乎几乎一样好:

var newCar2 = car with
{
    Riders = new Dictionary<string, Person>(car.Riders)
    {
        { "passenger1", new Person { Name = "Marty McFly" } }
    }
};

您是否希望避免new Dictionary... 部分?我不相信在当前版本的 C# 中这是可能的,即使在过去几个版本中进行了所有增强以支持集合初始化程序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-25
    • 1970-01-01
    相关资源
    最近更新 更多