简体   繁体   English

C#值类型列表

[英]C# Value Type Lists

I'm a bit confused. 我有点困惑。 Structs are more or less value types that get constructed on the stack and therefore have a straightforward lifetime. 结构或多或少是在堆栈上构造的值类型,因此寿命很简单。

When building a list with a struct, you cannot modify them directly because the returned value is a copy, and won't actually modify the item stored in the list. 使用结构构建列表时,您不能直接修改它们,因为返回的值是副本,并且实际上不会修改存储在列表中的项目。

My confusion comes here: Why can I not directly change a struct item in a list, but I can directly access and modify the base value types (int, float, etc...)? 我的困惑就在这里:为什么我不能直接更改列表中的struct项,但可以直接访问和修改基值类型(int,float等)?

This works: 这有效:

 List<int> foobar1 = new List<int>();
 foobar1.Add(1);
 foobar1[0] = 2;

This Doesn't: 这不是:

public struct foo
{
    public int bar;
}

...         

List<foo> foobar2 = new List<foo>();
foobar2.Add(new foo());
foobar2[0].bar = 2;

The two are fundamentally different, and not just because someone decided that it is, let me explain. 两者从根本上是不同的,不仅仅是因为有人认为是这样,让我解释一下。

The first piece of code replaces wholesale the int value in the 0th element position in the list. 第一段代码替换批发清单中第0个元素位置的int值。 It doesn't matter which int value is there, afterwards the list contains the int value 2 in the 0th position. 哪个int值无关紧要,之后列表在第0个位置包含int2

The second piece of code, however, is attempting to replace parts of the struct. 但是,第二段代码正在尝试替换该结构的某些部分 Yes, I know, the struct only has one field but the compiler makes no such distinction. 是的,我知道,该结构只有一个字段,但是编译器没有这种区别。 You're effectively modifying a copy of the struct retrieved from the list. 您正在有效地修改从列表中检索到的结构的副本。 This is not allowed. 这是不允许的。

So the first piece of code just stuffs a new value type into the list, the second piece of code tries to modify the value type from the list, which is a copy. 因此,第一段代码只是将新的值类型填充到列表中,第二段代码尝试从列表(即副本)中修改值类型。

So, can you change the second piece of code to be like the first, ie. 因此,您可以将第二段代码更改为类似于第一段代码吗? replace the element in the list completely? 完全替换列表中的元素?

Sure: 当然:

var temp = foobar[0];
temp.bar = 2;
foobar2[0] = temp; // no longer modifies the copy, but replaces the element

Basically, this right here: 基本上,这就是这里:

foobar2[0].bar = 2;
          ^    ^
          |    |

is the problem. 是问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM