我想使用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
}
答案 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)
答案 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);
}
}