gpt4 book ai didi

c# - 两个数组的元素引用一个对象

转载 作者:太空宇宙 更新时间:2023-11-03 19:59:47 25 4
gpt4 key购买 nike

我有以下代码:

struct NewType
{
public int val;
}

static void Main(string[] args)
{
NewType i = new NewType();
List<NewType> IList = new List<NewType>();

i.val = 1;
IList.Add(i);

i.val = 2;
IList.Add(i);
}

之后,如果我打印 IList 列表中的每个元素,结果将是 12和我想的相反 22

因为: enter image description here

有人告诉我为什么结果是12

最佳答案

这是因为NewType是一个struct,它作为值类型添加到列表中(对象的副本添加到列表中,而不是引用到原始对象)。

如果您将它从 struct 更改为 class 那么它将如您所料。该类通过引用传递。

看看Classes and Structs (C# Programming Guide)

A struct is a value type. When a struct is created, the variable to which the struct is assigned holds the struct's actual data. When the struct is assigned to a new variable, it is copied. The new variable and the original variable therefore contain two separate copies of the same data. Changes made to one copy do not affect the other copy.

关于c# - 两个数组的元素引用一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29693006/

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