Pass Method as Parameter using C#

后端 未结 12 1364
不知归路
不知归路 2020-11-21 23:30

I have several methods all with the same parameter types and return values but different names and blocks. I want to pass the name of the method to run to another method tha

12条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 00:31

    You need to use a delegate. In this case all your methods take a string parameter and return an int - this is most simply represented by the Func delegate1. So your code can become correct with as simple a change as this:

    public bool RunTheMethod(Func myMethodName)
    {
        // ... do stuff
        int i = myMethodName("My String");
        // ... do more stuff
        return true;
    }
    

    Delegates have a lot more power than this, admittedly. For example, with C# you can create a delegate from a lambda expression, so you could invoke your method this way:

    RunTheMethod(x => x.Length);
    

    That will create an anonymous function like this:

    // The <> in the name make it "unspeakable" - you can't refer to this method directly
    // in your own code.
    private static int <>_HiddenMethod_<>(string x)
    {
        return x.Length;
    }
    

    and then pass that delegate to the RunTheMethod method.

    You can use delegates for event subscriptions, asynchronous execution, callbacks - all kinds of things. It's well worth reading up on them, particularly if you want to use LINQ. I have an article which is mostly about the differences between delegates and events, but you may find it useful anyway.


    1 This is just based on the generic Func delegate type in the framework; you could easily declare your own:

    public delegate int MyDelegateType(string value)
    

    and then make the parameter be of type MyDelegateType instead.

提交回复
热议问题