Pass a method as an argument

后端 未结 5 1446
离开以前
离开以前 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<TResult> where TResult is string and lambdas.

    Your code would then become:

    protected void MyMethod(){
        RunMethod(() => ParamMethod("World"));
    }
    
    protected void RunMethod(Func<string> 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;
    }
    
    0 讨论(0)
  • 2020-12-31 20:40
    protected String ParamMethod(String sWho)
    {
        return "Hello " + sWho;
    }
    
    protected void RunMethod(Func<string> ArgMethod)
    {
        MessageBox.Show(ArgMethod());
    }
    
    protected void MyMethod()
    {
        RunMethod( () => ParamMethod("World"));
    }
    

    That () => is important. It creates an anonymous Func<string> from the Func<string, string> that is ParamMethod.

    0 讨论(0)
  • 2020-12-31 20:42

    Your ParamMethod is of type Func<String,String> 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<String,String> ArgMethod, String s){
        MessageBox.Show(ArgMethod(s));
    }
    
    protected String ParamMethod(String sWho){
        return "Hello " + sWho;
    }
    
    0 讨论(0)
  • 2020-12-31 20:48
    protected delegate String MyDelegate(String str);
    
    protected void MyMethod()
    {
        MyDelegate del1 = new MyDelegate(ParamMethod);
        RunMethod(del1, "World");
    }
    
    protected void RunMethod(MyDelegate mydelegate, String s)
    {
        MessageBox.Show(mydelegate(s) );
    }
    
    protected String ParamMethod(String sWho)
    {
        return "Hello " + sWho;
    }
    
    0 讨论(0)
  • 2020-12-31 21:03

    Take a look at C# Delegates

    http://msdn.microsoft.com/en-us/library/ms173171(VS.80).aspx

    Tutorial http://www.switchonthecode.com/tutorials/csharp-tutorial-the-built-in-generic-delegate-declarations

    0 讨论(0)
提交回复
热议问题