简体   繁体   English

为什么字符串列表未更新,而复杂 object 列表已更新

[英]Why is a list of string not updated, whereas list of complex object is updated

Case 1 - I have a list of string, say案例 1 - 我有一个字符串列表,比如说

List<string> source = new List<string>();`
source.Add("one");
source.Add("two");
source.Add("three");

If i update the value for "two" using below code, it wont update the value.如果我使用下面的代码更新“二”的值,它不会更新该值。

Example -例子 -

source.ForEach(x => {if (x == "two"){x = "twenty";}});

Case 2 - But when I have a List<ComplexObject> obj = new List<ComplexObject>() with two property Key, DisplayText with value as案例 2 - 但是当我有一个List<ComplexObject> obj = new List<ComplexObject>()具有两个属性键时,DisplayText 的值为

1,"One"
2, "two"

And I try to update using below code, the value will be updated我尝试使用下面的代码进行更新,值将被更新

 obj.ForEach(x => {if (x.Key == 2){ x.DisplayText = "Update value for 2";}});

Though both are list but why is the behaviour different?虽然两者都是列表,但为什么行为不同?

This problem refers to understanding how parameters works and what is delegate .这个问题是指理解参数是如何工作的以及什么是委托

The "thing" you pass in ForEach method is function , which has parameter, so it called Action delegate.您在 ForEach 方法中传递的“事物”是function ,它有参数,因此它称为Action委托。 This mean, that this is simple function with one single parameter.这意味着,这是简单的 function,只有一个参数。 So you need to remember, that "x"(your param name inside ForEach) is not exactly item, that placed inside your list, this is parameter, which have the same behavior with simple parameter of function.所以你需要记住,“x”(你在 ForEach 中的参数名称)并不完全是放在你的列表中的项目,这是参数,它与 function 的简单参数具有相同的行为。

In first case: string, as we know is reference type, but it has value type behavor, so you get no change of source value, because new variable created and chars inside string copied to chars of new variable.在第一种情况下:字符串,我们知道是引用类型,但它具有值类型行为,因此您不会更改源值,因为创建了新变量并将字符串中的字符复制到新变量的字符。

In second case: classes` objects in C# have references to their fileds in heap, so when item of your list proces inside ForEach and pass object like parameter, ComplexObject' object copy all the references to new object. In second case: classes` objects in C# have references to their fileds in heap, so when item of your list proces inside ForEach and pass object like parameter, ComplexObject' object copy all the references to new object. So it's also whole new variable, but references to fields remains the same所以它也是全新的变量,但对字段的引用保持不变

ForEach and various methods, which accept delegate works like simple loop with passing each item to this function(it's obviosly much complex, but for general understanding it`s ok). ForEach 和各种接受委托的方法就像简单的循环一样,将每个项目传递给这个函数(它显然非常复杂,但为了一般理解它是可以的)。

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

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