Pass a method as an argument

后端 未结 5 1531
离开以前
离开以前 2020-12-31 20:12

How do I pass a method as an argument? I do this all the time in Javascript and need to use anonymous methods to pass params. How do I do it in c#?

protecte         


        
5条回答
  •  失恋的感觉
    2020-12-31 20:42

    Your ParamMethod is of type Func because it takes one string argument and returns a string (note that the last item in the angled brackets is the return type).

    So in this case, your code would become something like this:

    protected void MyMethod(){
        RunMethod(ParamMethod, "World");
    }
    
    protected void RunMethod(Func ArgMethod, String s){
        MessageBox.Show(ArgMethod(s));
    }
    
    protected String ParamMethod(String sWho){
        return "Hello " + sWho;
    }
    

提交回复
热议问题