我如何将其他参数传递给MatchEvaluator

Jon*_*ury 22 c# matchevaluator

我有一些看起来像这样的代码:

text = reg.Replace(text, new MatchEvaluator(MatchEvalStuff));
Run Code Online (Sandbox Code Playgroud)

我需要传递第二个参数,如下所示:

text = reg.Replace(text, new MatchEvaluator(MatchEvalStuff, otherData));
Run Code Online (Sandbox Code Playgroud)

这是可能的,最好的方法是什么?

Dan*_*ted 26

MatchEvaluator是一个委托,因此您无法更改其签名.您可以创建一个使用附加参数调用方法的委托.使用lambda表达式非常容易:

text = reg.Replace(text, match => MatchEvalStuff(match, otherData));
Run Code Online (Sandbox Code Playgroud)


Jon*_*ury 13

对不起,我应该提到我使用2.0,所以我无法访问lambdas.这是我最终做的事情:

private string MyMethod(Match match, bool param1, int param2)
{
    //Do stuff here
}

Regex reg = new Regex(@"{regex goes here}", RegexOptions.IgnoreCase);
Content = reg.Replace(Content, new MatchEvaluator(delegate(Match match) { return MyMethod(match, false, 0); }));
Run Code Online (Sandbox Code Playgroud)

这样我就可以创建一个"MyMethod"方法并将其传递给我需要的任何参数(param1和param2仅用于此示例,而不是我实际使用的代码).