gpt4 book ai didi

c# - 不变性的真正定义?

转载 作者:太空狗 更新时间:2023-10-29 18:00:42 29 4
gpt4 key购买 nike

我想知道不变性是如何定义的?如果值不公开,因此无法修改,就足够了吗?

是否可以在类型内部修改值,而不是由类型的客户修改?

或者只能在构造函数中设置它们?如果是这样,在双重初始化的情况下(在结构上使用 this 关键字等)对于不可变类型仍然可以吗?

如何保证类型 100% 不可变?

最佳答案

If the values aren't exposed as public, so can't be modified, then it's enough?

不,因为您需要读取权限。

Can the values be modified inside the type, not by the customer of the type?

不,因为那仍然是突变。

Or can one only set them inside a constructor?

叮叮叮!另外一点,不可变类型通常具有构造和返回新实例的方法,并且通常具有标记为 internal 的额外构造函数,专门供这些方法使用。

How can I guarantee that the type is 100% immutable?

在 .Net 中,很难获得这样的保证,因为您可以使用反射来修改(变异)私有(private)成员。

关于c# - 不变性的真正定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/912858/

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