7

我正在尝试修改数组的值,但它没有被修改:

string buzones = File.ReadAllText("c:\\Buzones");
string[] buzoneslist = buzones.Split(',');

Array.ForEach(buzoneslist, x =>
{
    x = x.Replace(",", "");
});

这就像我在做一个字符串。替换而不将结果值设置为变量:

s.replace(",", "");代替 s=s.replace(",", "");

是否可以在 lambda 表达式中完成?

4

1 回答 1

22

No, you can't modify an array while you're enumerating it with ForEach, and strings are immutable so there's no function that will modify the instance in-place.

You could do either:

for (int i=0; i<buzoneslist.Length; i++) 
    buzoneslist[i] = buzoneslist[i].Replace(",", "");

Or:

buzoneslist = buzoneslist.Select(t => t.Replace(",", "")).ToArray();

I suppose if you really wanted to use a lambda, you could write an extension method:

public static class Extensions {
    public static void ChangeEach<T>(this T[] array, Func<T,T> mutator) {
        for (int i=0; i<array.Length; i++) {
            array[i] = mutator(array[i]);
        }
    }
}

And then:

buzoneslist.ChangeEach(t => t.Replace(",", ""));
于 2013-06-11T06:07:35.470 回答