gpt4 book ai didi

c# - IList 与 mutable_struct[]

转载 作者:太空狗 更新时间:2023-10-29 20:20:23 26 4
gpt4 key购买 nike

好的,让我们来一些代码:

//I complie nicely
ValueType[] good = new ValueType[1];
good[0].Name = "Robin";

//I don't compile: Cannot modify expression because its not a variable
IList<ValueType> bad = new ValueType[1];
bad[0].Name = "Jerome";

struct ValueType
{
public string Name;
}

究竟是什么导致编译器停滞不前?

//Adding to watch the following
good.GetType().Name //Value = "ValueType[]" It's a ValueType array.
bad.GetType().Name //Value = "ValueType[]" Also a ValueType array.

编译器阻止我修改我要更改的对象副本的成员。但是为什么要从这个数组中创建一个副本?

再进行一点研究:

var guess = (ValueType[]) bad;
guess[0].Name="Delilah";

现在,您认为 bad[0].Name 是什么?没错,就是“大利拉”。

最佳答案

Why is a value type being copy-returned from the IList<ValueType> but not from the array

因为数组是编译器已知的内置结构。它的运营商[]具有内置语义,它为编译器提供数组本身内部的可修改引用。

另一方面,当编译器处理一个接口(interface)时,它只知道它取回了您正试图修改的值类型的副本。换句话说,编译器查看 IList的运营商 []和数组的运算符 []不同。

注意:不用说,这个练习具有纯粹的学术值(value),因为mutable structs are evil .

关于c# - IList<mutable_struct> 与 mutable_struct[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26060663/

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