开发者

Pass Method ( of void return type and with no input arguments) as parameter using C#

开发者 https://www.devze.com 2023-01-31 23:45 出处:网络
I want to pass a method ( of void return type and with no input argumen开发者_Python百科ts)as parameter using C#. Below is my sample code. How can I do it ?

I want to pass a method ( of void return type and with no input argumen开发者_Python百科ts) as parameter using C#. Below is my sample code. How can I do it ?

public void Method1()
{
    ... do something
}

public int Method2()
{
    ... do something 
}

public void RunTheMethod([Method Name passed in here] myMethodName)
{

    myMethodName();
    ... do more stuff
}


System.Action will fit the bill:

http://msdn.microsoft.com/en-us/library/system.action.aspx

You've also got various generic versions of Action for methods that have parameters but have a void return type, and Func for methods that return something.

So your RunTheMethod method would look like

public void RunTheMethod(Action myMethod)
{
    myMethod();
}

Then you can call it with:

RunTheMethod(Method1);
RunTheMethod(Method2);


As mentioned before, you can use delegates – in your case, you could use System.Action to do exactly that.

public void RunTheMethod(System.Action myMethodName)
{

    myMethodName();
    ... do more stuff
}


Take a look at delegates which act like a pointer to a method


You should look at Delegates to get a solution to your query. They basically serve as a pointer or reference to a function.

Also take a look at this example for a better understanding.


//Delegate     
public delegate void OnDoStuff();

        class Program
        {
            static void Main(string[] args)
            {
                //Pass any of the method name here 
                Invoker(Method1);
                Console.ReadLine();
            }

            private static void Invoker(OnDoStuff method)
            {
                method.Invoke();
            }

            private static void Method1()
            {
                Console.WriteLine("Method1 from method " + i);
            }

            private static void Method2()
            {
                Console.WriteLine("Method2 from method " + i);
            }

            private static void Method3()
            {
                Console.WriteLine("Method3 from method " + i);
            }
        }
0

精彩评论

暂无评论...
验证码 换一张
取 消