传递方法并调用函数内部

时间:2013-03-14 12:36:54

标签: c# reflection

我有对象var channel = new Chanel(); 这个对象有几个我在函数内部调用的方法:

private bool GetMethodExecution()
{
   var channel = new Channel();
   channel.method1();
   channel.method2();
}

Channel的所有方法都来自接口IChannel。 我的问题是如何调用方法GetMethodExecution()并传递我想要执行的方法,然后根据传递的参数在此函数中执行它。

我需要调用GetMethodExectution(IChannle.method1),然后在此函数内的对象上调用它。这可能吗

4 个答案:

答案 0 :(得分:4)

private bool GetMethodExecution(Func<Channel, bool> channelExecutor)
{
   var channel = new Channel();
   return channelExecutor(channel);
}

现在你可以通过lambda传递方法,如:

GetMethodExecution(ch => ch.method1());

GetMethodExecution(ch => ch.method2());

答案 1 :(得分:1)

你在找这样的东西吗?

private bool GetMethodExecution(int method)
{
   switch (method)
   {
       case 1: return new Channel().method1();
       case 2: return new Channel().method2();
       default: throw new ArgumentOutOfRangeException("method");
   }
}
GetMethodExecution(1);
GetMethodExecution(2);

答案 2 :(得分:1)

您可以使用Func 代表

执行以下操作
private bool GetMethodExecution(Func<bool> Method)
{
    return Method()
}

public bool YourCallingMethod()
{
    var channel = new Channel();         
    return GetMethodExecution(channel.method1); // Or return GetMethodExecution(channel.method2);
}

答案 3 :(得分:0)

如果要将方法名称作为参数传递并在代码块中调用它,可以按如下方式使用反射:

private bool GetMethodExecution(string methodName)
{
   var channel = new Channel();

   Type type = typeof(Channel);
   MethodInfo info = type.GetMethod(methodName);

   return (bool)info.Invoke(channel, null); // # Assuming the methods you call return bool
}      
相关问题