Tutorial :How to convert a string to a « function signature » to create a delegate?



Question:

I'm trying to pass the name of a method from one class to another class, so the other class can "subscribe" her to an event that the first class is not aware of. Let's say I've got those classes:

class1  {    public void method1(string msg)    {      //does something with msg    }      public void i_make_a_class2()    {      class2 bob = new class2(method1);    }  }    class2  {    delegate void deleg(string msg);    deleg deleg1;      public class2(string fct)    {      // What I'm trying to do would go there with "fct" converted to function signature      deleg1 = new deleg(fct);      // Rest of the class constructor...    }    private void method2()    {      deleg1(im_a_String);    }  }  


Solution:1

You don't really want to pass the name of the function - you want to pass the delegate function itself - that's the key to delegates. Give me a minute and i'll write the code the way you want it.

Here you go:

public delegate void deleg(string msg);    public class class1  {    public void method1(string msg)    {      //does something with msg    }      public void i_make_a_class2()    {      class2 bob = new class2(method1);    }  }    public class class2  {    deleg deleg1;    string im_a_String = "Test";      public class2(deleg fct)    {      deleg1 = fct;      // Rest of the class constructor...    }    private void method2()    {      deleg1(im_a_String);    }  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »