Referencing a function in a variable?

后端 未结 4 1822
攒了一身酷
攒了一身酷 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: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 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).

提交回复
热议问题