gpt4 book ai didi

java - .NET 中的不可变列表 : Why are you allowed to add and remove items?

转载 作者:行者123 更新时间:2023-11-30 07:40:48 26 4
gpt4 key购买 nike

在 C# 中,我只是需要一个不可变列表,这意味着该列表不能更改

很像 Java 的不可变列表:https://www.geeksforgeeks.org/immutable-list-in-java/

从那里:

If any attempt is made to add null element in List, UnsupportedOperationException is thrown.

现在,在 .NET 中(至少在 Core 2.2 中)还有一个不可变列表,记录在案 here .

他们说(强调我的):

When you add or remove items from an immutable list, a copy of the original list is made with the items added or removed, and the original list is unchanged.

所以,这个实现基本上允许更改列表(通过每次获取一个操作副本),这与 java 理解相反,而且,它主要会在未被发现的情况下堵塞内存。

拥有一个首先支持添加和删除方法的不可变列表有什么意义?

这里对我来说的问题是,我的代码的用户会得到一个列表,大概是不可变的,但出于疏忽会很高兴地添加项目,这些项目永远不会进入原始“存储库”。这会造成混淆。

我想(唯一的)方法是使用 IEnumerale 接口(interface),以完全禁止操纵并向代码用户明确说明?

最佳答案

What's the point in having an immutable list that supports add and remove methods in the first place?

只有遵守 List 契约,即使不可变的实现也会暴露每一个 List 方法。
在您有两种方法来应对这些修改方法之后:抛出异常或通过在每次修改时创建并返回一个新列表来保证不变性。

关于:

I guess the (only) way to go here, to forbid manipulation entirely, would be to use the IEnumerale interface?

事实上,在 Java 中,当您希望能够操纵一组事物而无需更改它时,您可以使用 Iterable(这已经足够接近了)。
作为替代方案,您也可以使用数组。

关于java - .NET 中的不可变列表 : Why are you allowed to add and remove items?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57006453/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com