.NET 中的不可变列表:为什么允许添加和删除项目?
Immutable list in .NET: Why are you allowed to add and remove items?
在 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 理解相反,此实现基本上允许更改列表(通过每次获取一个操作副本),更重要的是,它几乎不会被检测到堵塞内存。
首先支持添加和删除方法的不可变列表有什么意义?
我的问题是,我的代码的用户会得到一个列表,大概是不可变的,但出于疏忽会很乐意添加项目,这些项目永远不会成为原始 "repository"。这会造成混淆。
我想(唯一的)方法是使用 IEnumerale 接口,以完全禁止操纵,并让代码用户清楚地知道?
正如您所说:“原始列表的副本是添加或删除的项目,原始列表保持不变。”。
因此您可以 add/remove 个元素,并根据更改创建一个新列表。原榜单不变
What's the point in having an immutable list that supports add and remove methods in the first place?
首先考虑一下:不支持以任何方式添加或删除项目的不可变列表有什么意义?没有什么特别有用的。您可以为此使用数组。
现在回到你的问题。该列表是不可变的,因此消费者无法更改通过其他方法或 class 提供的实例本身。消费者无法更改后备存储!但是不可变列表的生产者可以通过创建一个新的不可变列表并将其分配给原始变量来 'alter' 后备存储。是不是很有用!
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
(这已经足够接近了)。
作为替代方案,您也可以使用数组。
在 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 理解相反,此实现基本上允许更改列表(通过每次获取一个操作副本),更重要的是,它几乎不会被检测到堵塞内存。
首先支持添加和删除方法的不可变列表有什么意义?
我的问题是,我的代码的用户会得到一个列表,大概是不可变的,但出于疏忽会很乐意添加项目,这些项目永远不会成为原始 "repository"。这会造成混淆。
我想(唯一的)方法是使用 IEnumerale 接口,以完全禁止操纵,并让代码用户清楚地知道?
正如您所说:“原始列表的副本是添加或删除的项目,原始列表保持不变。”。
因此您可以 add/remove 个元素,并根据更改创建一个新列表。原榜单不变
What's the point in having an immutable list that supports add and remove methods in the first place?
首先考虑一下:不支持以任何方式添加或删除项目的不可变列表有什么意义?没有什么特别有用的。您可以为此使用数组。
现在回到你的问题。该列表是不可变的,因此消费者无法更改通过其他方法或 class 提供的实例本身。消费者无法更改后备存储!但是不可变列表的生产者可以通过创建一个新的不可变列表并将其分配给原始变量来 'alter' 后备存储。是不是很有用!
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
(这已经足够接近了)。
作为替代方案,您也可以使用数组。