Last post Apr 09, 2009 11:08 PM by SGWellens
Apr 09, 2009 03:41 PM|pkellner|LINK
I have a method that always has the same signature but the name changes a little. An example is below. Suggestions? (that is, what is the code to generate the call to Method9 when you form the name on the fly.
for (int i=0;i<10;i++)
string myMethodName = "Method" + i.ToString();
CALL METHOD WITH DYNAMIC NAME
THAT IS Method9("stringvalue",999,true);
class public void Method9(string str,int iVal,bool printit)
class public void Method10(string str,int iVal,bool printit)
Apr 09, 2009 03:46 PM|mbanavige|LINK
I'd say use Reflection. like in this sample:
Although, if the number of methods is low, you might also want to consider a switch and then execute the actual methods directly. Using Reflection to execute a method is much slower than executing that method directly.
Apr 09, 2009 06:05 PM|JeffreyABecker|LINK
Do all the methods have the same signature and are they known at compile time?
Apr 09, 2009 08:13 PM|pkellner|LINK
Yeah, every member has the same signature. I use a switch now, but it's a hassle to add a new switch item each time I add a new method. It's a template processing app so it would be convenient if I could just add methods and they would "magically" be found.
I'm just being lazy. Speed is not a problem. It's for code generation and I don't do that very often (thankfully).
Apr 09, 2009 10:30 PM|pkellner|LINK
The article referenced by Mike above worked out perfect! I decided to write a blog post so next time I don't have to look so hard. Here it is, and thanks Mike!
Apr 09, 2009 11:08 PM|SGWellens|LINK
Could it have been done this way? (this solution depends on sequential function access but a dictionary could have been used).
public delegate int MyDelegate(String Msg);
protected void Button1_Click(object sender, EventArgs e)
List<MyDelegate> Router = new List();
Router.Add(null); // want index to start at 1
int Status = Router("xyz");
public int Talk1(String Msg)
public int Talk2(String Msg)
Label1.Text = Msg;
public int Talk3(String Msg)