A quick and dirty way to pass a method with parameters as a parameter?

Let me just preface this with the fact that I'm pretty green for C #. In doing so, I am looking for a way to pass a method with parameters as a parameter. Ideally, I want to do the following:

static void Main(string[] args)
{
    methodQueue ( methodOne( x, y ));
}

static void methodOne (var x, var y)
{
    //...do stuff
}

static void methodQueue (method parameter)
{
    //...wait
    //...execute the parameter statement
}

Can someone point me in the right direction?

+3
source share
5 answers

This should do what you want. In fact, this is passed without parameters for your function, but delegate () {methodOne (1, 2);} creates an anonymous function that calls the One method with the appropriate parameters.

I wanted to test this before introducing it, but only has the .net framework 2.0, hence my approach.

public delegate void QueuedMethod();

static void Main(string[] args)
{
    methodQueue(delegate(){methodOne( 1, 2 );});
    methodQueue(delegate(){methodTwo( 3, 4 );});
}

static void methodOne (int x, int y)
{

}

static void methodQueue (QueuedMethod parameter)
{
    parameter(); //run the method
    //...wait
    //...execute the parameter statement
}
+4

// Using Action<T>

using System;
using System.Windows.Forms;

public class TestAction1
{
   public static void Main()
   {
      Action<string> messageTarget; 

      if (Environment.GetCommandLineArgs().Length > 1)
         messageTarget = ShowWindowsMessage;
      else
         messageTarget = Console.WriteLine;

      messageTarget("Hello, World!");   
   }      

   private static void ShowWindowsMessage(string message)
   {
      MessageBox.Show(message);      
   }
}
+4

, void, . - :

< > public void Main() { MethodQueue(MethodOne); } public void MethodOne(int x, int y) { // do stuff } public void MethodQueue(Action<int, int> method) { // wait method(0, 0); } Func, .

+2

, . ,

 class Program
 {
    static void Main(string[] args)
    {
        MethodQueue(() => MethodOne(1, 2));
    }

    static void MethodOne(int x, int y)
    {...}

    static void MethodQueue(Action act)
    {
        act();
    }


 }
+2

C- , , .

0

Source: https://habr.com/ru/post/1732299/


All Articles