我刚开始使用Lambda表达式等相关知识。然而,在这种情况下,我不知道需要提供什么参数。
我试图修改字符串以替换字典中所有条目的值,这并不是很花哨,我可以使用简单的foreach
循环来实现,但我正在尝试将其作为学习练习。
到目前为止,我的代码如下:
string maskString = Masks[alias];
Regex regex = new Regex(@"({[\w+|\d]+})");
MatchCollection matches = regex.Matches(maskString);
string[] constants = matches.Cast<Match>().Select(m => m.Value).ToArray();
string maskedString = "";
if (constants.All(constant => Constants.ContainsKey(constant)))
{
constants.ForEach(constant => maskedString = maskedString.Replace(constant, Constants[constant]));
}
然而,我收到了这个错误:
There is no argument given that corresponds to the required formal parameter 'action' of 'Array.ForEach<T>(T[], Action<T>)'
。在我的看法中,我以lambda
表达式的形式提供了操作,但我不知道为什么它需要另一个数组或者我应该给它什么数组。
我尝试过提供null
、string[]
和new [] {typeof(string)}
,但这些只会引起更多的错误。
是否可能使用这种结构来进行此操作,或者使用传统的foreach
循环更实际?
Array.ForEach(constants, constant => maskedString = maskedString.Replace(constant, Constants[constant]));
无论如何,在涉及“副作用”时,我更喜欢使用标准的foreach循环。 - digEmAll的扩展方法,但不是
[]`? - ScottishTapWaterArray.ForEach
,它是一个静态的非扩展方法。对于List<T>.ForEach
,它是一个常规实例方法。对于其他的IEnumerable<T>
,没有标准的ForEach
可以调用,无论是扩展方法还是非扩展方法。 - user743382