在列表与下更改元素的值; T> .ForEach的ForEach方法 [英] Changing element value in List<T>.ForEach ForEach method
本文介绍了在列表与下更改元素的值; T> .ForEach的ForEach方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
newsplit.ToList().ForEach(x => x = "WW");
我期望列表中的所有元素现在是WW,但他们仍然是原来的值。怎么来的?我有什么做的有什么不同?
I would expect that all elements in the list are now "WW" but they are still the original value. How come? What do I have to do different?
推荐答案
假设 newsplit
是一个的IEnumerable<串>
,你想要的:
Assuming that newsplit
is an IEnumerable<string>
, you want:
newsplit = newsplit.Select(x => "WW");
这是您当前拥有的代码等同于以下内容:
The code that you currently have is equivalent to the following:
foreach(string x in newsplit.ToList()) {
AssignmentAction(x);
}
...
public static void AssignmentAction(string x) {
x = "WW";
}
这方法不会修改 X
因为C#和字符串的不变性的传递值语义的。
This method won't modify x
because of the pass-by-value semantics of C# and the immutability of strings.
这篇关于在列表与下更改元素的值; T> .ForEach的ForEach方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文