不可变对象中是否允许使用指针?

发布于 2024-10-16 06:35:46 字数 210 浏览 4 评论 0原文

C# 中的字典键(可能在大多数语言中)必须是不可变的。

我现在考虑使我的密钥的值依赖于另一个对象的某些属性的可能性。

一般来说,不可变对象可以有一个指向另一个对象的指针——或者不是?
当我更改另一个对象时,不可变对象没有改变它的状态。
但现在它的行为可能有所不同。

对于不可变对象允许这样做吗?
它被认为是不好的做法还是相反的好做法?

Dictionary keys in C# (probably in most languages) must be immutable.

I consider now the possiblity to make the value of my key to depend on some property of another object.

Generally speaking an immutable object could have a pointer to another object - or not?
When I change this other object, the immutable object didn't change it's state.
But it's behaviour may be different now.

Is this allowed for immutable objects?
Is it considered bad practice or on the contrary good practice?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

旧伤慢歌 2024-10-23 06:35:46

您可以在不可变对象中拥有指针,这是浅不变性与深层不变性之间的区别。

查看 MSDN 博客文章 C# 中的不变性第一部分:不变性的种类

You can have pointers in an immutable object, it's the difference between shallow vs deep immutability.

Have a look at the MSDN blog post Immutability in C# Part One: Kinds of Immutability

々眼睛长脚气 2024-10-23 06:35:46

让一个对象持有对可变对象的不可变引用并没有什么问题。事实上,这有时是一种有用的模式。例如,集合可能公开许多枚举方法。实现此目的的最简单方法可能是定义多个结构,每个结构包含一项:对集合的引用,并通过调用集合中的适当方法来实现 IEnumerable.GetEnumerator。例如,结构 MyMultiSortedKeyDictionary.EnumeratorByFirstKey 将保存对 MyMultiSortedkeyDictionary 的引用,并通过在根集合上调用 GetFirstKeyEnumerator 来实现 IEnumerable.GetEnumerator。结构 .EnumeratorBySecondKey 类似,但会调用 GetSecondKeyEnumerator。两种结构都是不可变的,但每个结构都保存对可变对象的引用。

There is nothing wrong with having an object hold an immutable reference to a mutable object. Indded, that can sometimes be a useful pattern. For example, a collection might expose numerous methods of enumeration. The simplest way to achieve this may be to define a number of structures each of which holds one item: a reference to the collection, and implements IEnumerable.GetEnumerator by calling an appropriate method in the collection. For example, a structure MyMultiSortedKeyDictionary.EnumeratorByFirstKey would hold a reference to a MyMultiSortedkeyDictionary and implement IEnumerable.GetEnumerator by calling GetFirstKeyEnumerator on the root collection. A structure .EnumeratorBySecondKey would be similar, but would call GetSecondKeyEnumerator. Both structures would be immutable, but each would hold a reference to a mutable object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文