我有一些代碼,看起來像這樣:如何將其他參數傳遞到MatchEvaluator
text = reg.Replace(text, new MatchEvaluator(MatchEvalStuff));
我需要在第二個參數來傳遞這樣的:
text = reg.Replace(text, new MatchEvaluator(MatchEvalStuff, otherData));
這是可能的,那麼最好的辦法是什麼?
我有一些代碼,看起來像這樣:如何將其他參數傳遞到MatchEvaluator
text = reg.Replace(text, new MatchEvaluator(MatchEvalStuff));
我需要在第二個參數來傳遞這樣的:
text = reg.Replace(text, new MatchEvaluator(MatchEvalStuff, otherData));
這是可能的,那麼最好的辦法是什麼?
對不起,我應該提到,我使用的是2.0,所以我沒有訪問lambda表達式。以下是我落得這樣做:
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」的方法,並通過它,我需要的任何參數(參數1和參數都只是爲了這個例子,不是我實際使用的代碼) 。
MatchEvaluator是一個委託,所以你不能改變它的簽名。您可以創建一個使用其他參數調用方法的委託。這是很容易用lambda表達式做:
text = reg.Replace(text, match => MatchEvalStuff(match, otherData));
非常感謝!我喜歡這個答案 – 2014-11-07 14:18:49