Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I pass additional parameters to MatchEvaluator

I have a bit of code that looks like this:

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

I need to pass in a 2nd parameter like this:

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

Is this possible, and what would be the best way to do this?

like image 469
Jon Tackabury Avatar asked Nov 20 '08 19:11

Jon Tackabury


2 Answers

MatchEvaluator is a delegate so you can't change its signature. You can create a delegate that calls a method with an additional parameter. This is pretty easy to do with lambda expressions:

text = reg.Replace(text, match => MatchEvalStuff(match, otherData));
like image 123
Daniel Plaisted Avatar answered Nov 20 '22 00:11

Daniel Plaisted


Sorry, I should have mentioned that I'm using 2.0, so I don't have access to lambdas. Here is what I ended up doing:

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); }));

This way I can create a "MyMethod" method and pass it whatever parameters I need to (param1 and param2 are just for this example, not the code I actually used).

like image 14
Jon Tackabury Avatar answered Nov 20 '22 00:11

Jon Tackabury