使用C#传递方法(void返回类型且没有输入参数)作为参数

时间:2010-12-22 12:36:11

标签: c# generics c#-3.0 delegates

我想使用C#传递一个方法(void返回类型,没有输入参数)作为参数。以下是我的示例代码。我该怎么办?

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

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

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

    myMethodName();
    ... do more stuff
}

5 个答案:

答案 0 :(得分:7)

System.Action符合条例草案:

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

对于具有参数但具有void返回类型的方法,您还获得了Action的各种泛型版本,对于返回某些内容的方法,还有Func。

所以你的RunTheMethod方法看起来像

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

然后你可以用:

来调用它
RunTheMethod(Method1);
RunTheMethod(Method2);

答案 1 :(得分:1)

如前所述,您可以使用代理 - 在您的情况下,您可以使用System.Action来完成此操作。

public void RunTheMethod(System.Action myMethodName)
{

    myMethodName();
    ... do more stuff
}

答案 2 :(得分:0)

看一下delegates,它就像一个指向方法的指针

答案 3 :(得分:0)

您应该查看Delegates以获得查询的解决方案。它们基本上用作函数的指针或引用。

另请查看this示例,以便更好地理解。

答案 4 :(得分:0)

//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);
            }
        }