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

Roc*_*ngh 1 c# generics delegates c#-3.0

我想使用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
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*ins 7

System.Action符合法案:

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

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

所以你的RunTheMethod方法看起来像

public void RunTheMethod(Action myMethod)
{
    myMethod();
}
Run Code Online (Sandbox Code Playgroud)

然后你可以用:

RunTheMethod(Method1);
RunTheMethod(Method2);
Run Code Online (Sandbox Code Playgroud)