【发布时间】:2017-03-18 11:27:10
【问题描述】:
我正在尝试对 int 类型列表中的所有数字求平方。但是,当我运行代码时,列表似乎根本没有改变。
public static List<int> SquareList(List<int> root)
{
root.ForEach(x => x = x*x);
return root;
}
x_unit 中的测试类。
[Fact]
public void testSqures()
{
var input = new List<int> { 1, 2, 3 };
var expected = new List<int> { 1, 4, 9 };
var result = Square.SquareList(input);
Assert.Equal(expected,result);
}
问题foreach 操作符不会改变底层对象吗?
我需要创建一个新列表吗?还是有办法将列表转换到位?
【问题讨论】:
-
来自 MSDN:不支持修改
Action<T>委托主体中的基础集合,并导致未定义的行为。 -
您正在使用值类型,并且无法在
Action委托中更新值类型。您肯定需要创建一个新列表。