Passing in Function name to be called
-
Is there any way to have a function that accepts a function name as a parameter and is then able to call it? EXAMPLE: public void MyFunc(Function func) { func(); } Help is greatly appreciated.
-
Is there any way to have a function that accepts a function name as a parameter and is then able to call it? EXAMPLE: public void MyFunc(Function func) { func(); } Help is greatly appreciated.
The following is a quick example of a delegate in C#.
using System; namespace Test { class Class1 { delegate void Func(int i); static void Main(string[] args) { Func f = new Func(SomeMethod); f(4); } public static void SomeMethod(int i) { Console.WriteLine("Hello from SomeMethod. " + i + " was passed in."); Console.Read(); } } }
-Nick Parker DeveloperNotes.com
-
Is there any way to have a function that accepts a function name as a parameter and is then able to call it? EXAMPLE: public void MyFunc(Function func) { func(); } Help is greatly appreciated.
Call the funcitzon "by name": public void MyFunc(Function func) { //get the type of the object containing the method Type type = this.GetType(); //get the method System.Reflection.MethodInfo methodInfo = type.GetMethod(func, BindingFlags.Default); String result; if(methodInfo == null){ result = TextConstants.MSG_MethodNotFound.Replace("Method not found"); }else{ //call the method result = methodInfo.Invoke(this, null).ToString(); } }