28

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

text = reg.Replace(text, new MatchEvaluator(MatchEvalStuff));

我需要像这样传递第二个参数:

text = reg.Replace(text, new MatchEvaluator(MatchEvalStuff, otherData));

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

4

2 回答 2

31

MatchEvaluator 是一个委托,因此您无法更改其签名。您可以创建一个调用带有附加参数的方法的委托。使用 lambda 表达式很容易做到这一点:

text = reg.Replace(text, match => MatchEvalStuff(match, otherData));
于 2008-11-20T19:34:02.913 回答
14

抱歉,我应该提到我使用的是 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); }));

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

于 2008-11-20T19:56:12.777 回答