Pass a method as an argument

后端 未结 5 1536
离开以前
离开以前 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:40

    Delegates provide this mechanism. A quick way to do this in C# 3.0 for your example would be to use Func where TResult is string and lambdas.

    Your code would then become:

    protected void MyMethod(){
        RunMethod(() => ParamMethod("World"));
    }
    
    protected void RunMethod(Func method){
        MessageBox.Show(method());
    }
    
    protected String ParamMethod(String sWho){
        return "Hello " + sWho;
    }
    

    However, if you are using C#2.0, you could use an anonymous delegate instead:

    // Declare a delegate for the method we're passing.
    delegate string MyDelegateType();
    
    protected void MyMethod(){
        RunMethod(delegate
        {
            return ParamMethod("World");
        });
    }
    
    protected void RunMethod(MyDelegateType method){
        MessageBox.Show(method());
    }
    
    protected String ParamMethod(String sWho){
        return "Hello " + sWho;
    }
    

提交回复
热议问题