Referencing a function in a variable?

后端 未结 4 1796
攒了一身酷
攒了一身酷 2021-01-11 23:42

Say I have a function. I wish to add a reference to this function in a variable.

So I could call the function \'foo(bool foobar)\' from a variable \'bar\', as if it

相关标签:
4条回答
  • 2021-01-12 00:20

    Are you looking for Delegates?

    0 讨论(0)
  • 2021-01-12 00:27

    It sounds like you want to save a Func to a variable for later use. Take a look at the examples here:

    using System;
    
    public class GenericFunc
    {
       public static void Main()
       {
          // Instantiate delegate to reference UppercaseString method
          Func<string, string> convertMethod = UppercaseString;
          string name = "Dakota";
          // Use delegate instance to call UppercaseString method
          Console.WriteLine(convertMethod(name));
       }
    
       private static string UppercaseString(string inputString)
       {
          return inputString.ToUpper();
       }
    }
    

    See how the method UppercaseString is saved to a variable called convertMethod which can then later be called: convertMethod(name).

    0 讨论(0)
  • 2021-01-12 00:41

    Using delegates

        void Foo(bool foobar)
        {
    /* method implementation */
        }
    

    using Action delegate

    Public Action<bool> Bar;
    Bar = Foo;
    

    Call the function;

    bool foobar = true;
    Bar(foobar);
    
    0 讨论(0)
  • 2021-01-12 00:43

    You need to know the signature of the function, and create a delegate.

    There are ready-made delegates for functions that return a value and for functions that have a void return type. Both of the previous links point to generic types that can take up to 15 or so type arguments (thus can serve for functions taking up to that many arguments).

    If you intend to use references to functions in a scope larger than a local scope, you can consider defining your own custom delegates. But most of the time, Action and Func do very nicely.

    Update:

    Take a look at this question regarding the choice between defining your own delegates or not.

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