代码之家  ›  专栏  ›  技术社区  ›  Apocalisp

如何将其他参数传递给MatchEvaluator

  •  21
  • Apocalisp  · 技术社区  · 16 年前

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

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

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

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

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

    2 回复  |  直到 16 年前
        1
  •  25
  •   Daniel Plaisted    16 年前

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

    text = reg.Replace(text, match => MatchEvalStuff(match, otherData));
    
        2
  •  12
  •   Apocalisp    16 年前

    抱歉,我应该提到我使用的是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”方法,并将它传递给我需要的任何参数(param1和param2只是这个示例,而不是我实际使用的代码)。