'列表 .foreach()'和可变性
-
15-11-2019 - |
题
我想将所有点转换为List<T>
。这有效:
for (int i = 0; i <PolygonBase.Count; ++i)
{
PolygonBase[i] = PolygonBase[i] + MousePos;
}
.
但使用 List<T>.ForEach
't:
PolygonBase.ForEach(v => v += MousePos);
.
想法?
解决方案
Your current code is simply re-assigning the local variable v
to a new value - it doesn't refer back to the original value in the list. It's the equivalent of writing:
foreach(int v in PolygonBase)
{
v += MousePos;
}
To write back to the original value, use ConvertAll
:
PolygonBase.ConvertAll(v => v += MousePos);
其他提示
ForEach is not mutable, it doesn't change the data structure in any way. Check out this threat. Using conditional lambda statements with a foreach Action on a list
不隶属于 StackOverflow