gpt4 book ai didi

c# - 什么时候对不可变类型使用值和引用类型? (。网)

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

对于可变类型,值类型和引用类型之间的行为差​​异很明显:

// Mutable value type
PointMutStruct pms1 = new PointMutStruct(1, 2);
PointMutStruct pms2 = pms1;
// pms1 == (1, 2); pms2 == (1, 2);
pms2.X = 3;
MutateState(pms1); // Changes the X property to 4.
// pms1 == (1, 2); pms2 == (3, 2);

// Mutable reference type
PointMutClass pmc1 = new PointMutClass(1, 2);
PointMutClass pmc2 = pmc1;
// pmc1 == (1, 2); pmc2 == (1, 2);
pmc2.X = 3;
MutateState(pmc1); // Changes the X property to 4.
// pmc1 == (4, 2); pmc2 == (4, 2);

然而,对于不可变类型,这种区别就不那么明显了:

// Immutable value type
PointImmStruct pis1 = new PointImmStruct(1, 2);
PointImmStruct pis2 = pis1;
// pis1 == (1, 2); pis2 == (1, 2);
pis2 = new PointImmStruct(3, pis2.Y);
// Can't mutate pis1
// pis1 == (1, 2); pis2 == (3, 2);

// Immutable reference type
PointImmClass pic1 = new PointImmClass(1, 2);
PointImmClass pic2 = pic1;
// pic1 == (1, 2); pic2 == (1, 2);
pic2 = new PointImmClass(3, pic2.Y);
// Can't mutate pic1 either
// pic1 == (1, 2); pic2 == (3, 2);

不可变引用类型也经常使用值语义(例如典型示例 System.String):

string s1 = GenerateTestString(); // Generate identical non-interned strings
string s2 = GenerateTestString(); // by dynamically creating them
// object.ReferenceEquals(strA, strB)) == false;
// strA.Equals(strB) == true
// strA == strB

Eric Lippert 之前在他的博客(例如 here)上讨论过,值类型通常(何时对本次讨论无关紧要)分配在堆栈上的事实是一个实现细节,它不应该通常决定您是将对象设为值类型还是引用类型。

鉴于不可变类型在行为上的这种模糊区分,这为我们留下什么标准来决定是将不可变类型设为引用类型还是值类型?

此外,由于强调值与变量的不可变性,不可变类型是否应该始终实现值语义?

最佳答案

我会说你链接的 Eric 的博客文章给了你确切的答案:

I regret that the documentation does not focus on what is most relevant; by focusing on a largely irrelevant implementation detail, we enlarge the importance of that implementation detail and obscure the importance of what makes a value type semantically useful. I dearly wish that all those articles explaining what “the stack” is would instead spend time explaining what exactly “copied by value” means and how misunderstanding or misusing “copy by value” can cause bugs.

如果您的对象应该具有“按值复制”语义,则将它们设为值类型。如果它们应该具有“按引用复制”语义,请将它们设为引用类型。

他也这么说,我同意:

I’d always make the choice of value type vs reference type based on whether the type is semantically representing a value or semantically a reference to something.

关于c# - 什么时候对不可变类型使用值和引用类型? (。网),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5971946/

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