Pass method and call inside function

I have an object var channel = new Chanel(); this object has several methods that I call inside the function as follows:

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

all Channel class methods come from the IChannel interface. My question is: how can I call the GetMethodExecution() method and pass the method that I want to execute, and then execute it inside this function based on the passed parameter.

I need to call GetMethodExectution (IChannle.method1) and then call it on an object inside this function. Is it possible,

+4
source share
4 answers
 private bool GetMethodExecution(Func<Channel, bool> channelExecutor) { var channel = new Channel(); return channelExecutor(channel); } 

Now you can pass the method using lambda:

 GetMethodExecution(ch => ch.method1()); GetMethodExecution(ch => ch.method2()); 
+4
source

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); 
+1
source

You can do it this way: 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); } 
+1
source

If you want to pass the method name as a parameter and call 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 } 
0
source

Source: https://habr.com/ru/post/1469229/


All Articles