ForEach不会更改/更改列表C#中的项目 [英] ForEach will not alter/change items in list C#
问题描述
我很确定这在我编写的某些代码中已经奏效,不确定我在这里缺少什么.
I'm pretty sure this has worked before in some code I have written, not sure what I am missing here.
以下代码不会更改列表中的 string
值.为什么?
The following code does not change the string
values in my list. Why?
var items = listBox1.Items.Cast<string>().ToList();
items.ForEach(item => item = (!chkBox1.Checked) ? "move " + item : "move -check " + item);
编辑:为澄清起见,列表与创建时相同.
EDIT : Just to clarify, the list remains the same as when it was created.
编辑:抱歉,项目列表(listBox1.Items)包含字母数字字符串,如下所示.
EDIT : Apologies, the items list (listBox1.Items) contains alphanumeric strings as follows.
J00123456
J00123344
J00123458
另外,为了确认这一点,我已经使用T的自定义列表(如下所示)成功完成了此操作,这就是为什么我认为它可以在此处使用的原因.
Also, just to confirm, I have successfully done this with a custom list of T (shown below), which is why I thought it would work here.
var tapes = new List<TapeInfo>();
... //Populated list
tapes.ForEach(x => x.vItem = "tapelib 3592 -eject " + x.vItem); //Works here
推荐答案
如果要获得不同的结果,则应使用 Select
函数.
You should use the Select
function if you want to get a different result.
var items = listBox1.Items.Cast<string>().ToList();
listBox1.Items = items.Select(item => (!chkBox1.Checked) ? "move " + item : "move -check " + item).ToList();
ForEach
函数可以根据集合值执行某些操作,但不能对值本身执行操作.
The ForEach
function can do something according to a collection value, but can't do it to the values themselves.
Select
函数将根据给定的集合创建一个新的集合.
The Select
function will create a new collection according to the given collection.
修改
关于使用来成功更改值的编辑
About your edit of successfully changing values by using
tapes.ForEach(x => x.vItem = "tapelib 3592 -eject " + x.vItem);
您需要了解按值/引用传递参数的工作方式.
You need to understand how passing argument by value/reference works.
在c#中,当编写 var obj1 = new object()
时, obj1
是指向存在于 new object()
上的指针堆.
In c#, when writing var obj1 = new object()
, obj1
is a pointer to the new object()
that exists on the heap.
当您通过调用 Foo(obj1)
将 obj1
传递给函数 public void Foo(object obj){//...}
时>,该函数会将参数作为 new 指针指向堆上的相同 对象
.
When you pass obj1
to a function public void Foo(object obj) { //... }
by calling Foo(obj1)
, the function will get the parameter as new pointer to the same object
on the heap.
因此,当您在对象本身上使用ForeEach时,
Therefore, when you use ForeEach on the object itself,
object.ForEach(obj => obj = new object()) // No changed outside the Foreach
只有新的指针会被更改,它将指向一个新的对象,但原始的指针不会被更改.
only the new pointer will be changed and it will point on a new object but the original pointer isn't changed.
但是如果在内部对象上使用它,
But if you use it on an inner object,
object.ForEach(obj => obj.InnerObject = new object()) // Changed outside the Foreach
这将更改指向的内部对象,并且内部对象也将更改.
this will change the pointed inner object and the inner object will be changed.
这篇关于ForEach不会更改/更改列表C#中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!