简体   繁体   English

传递方法并调用内部函数

[英]Pass method and call inside function

i have object var channel = new Chanel(); 我有对象var channel = new Chanel(); this object has several methods which i call inside function like this: 这个对象有几种方法,我在函数内部这样调用:

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

all methods of class Channel derives from interface IChannel . Channel类的所有方法都从接口IChannel派生。 My question is how can i call method GetMethodExecution() and pass which method I want to execute and then execute it inside this function based on parameter passed. 我的问题是如何调用方法GetMethodExecution()并传递要执行的方法 ,然后根据传递的参数在此函数内执行它。

What i need is to call GetMethodExectution(IChannle.method1) and then call it on object inside this function. 我需要的是调用GetMethodExectution(IChannle.method1),然后在此函数内的对象上调用它。 Is this possible 这可能吗

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

Now you can pass method via lambda like: 现在,您可以通过lambda传递方法,例如:

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

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

Are you looking for something like this? 您是否正在寻找这样的东西?

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

You can do it as following using Func Delegate : 您可以使用Func Delegate进行以下操作:

private bool GetMethodExecution(Func<bool> Method)
{
    return Method()
}

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

If you want to pass method name as parameter and Invoke it inside your code block, you can use reflection as follows: 如果要将方法名称作为参数传递并在代码块内调用它,则可以按如下所示使用反射:

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
}      

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM