Further Down the Rat Hole


Well, how could we do that Perform thing? Surely C# has some way to invoke a method given its name . Only a half hour or so of experimentation later, I had this code working:

 void MenuInsertSection(object obj, EventArgs ea) { 
model.SetLines(textbox.Lines);
model.SelectionStart = textbox.SelectionStart;

Type modelType = typeof(TextModel);
modelType.InvokeMember(
"InsertSectionTags",
BindingFlags.Default BindingFlags.InvokeMethod,
null,
model,
new object[]{});

PutText(textbox, model.LinesArray(), model.SelectionStart);
}

That atrocity in the middle is the code to invoke a method on an object, given the string name of the method. After, I swear, only a little more study, I found that you can say:

 model.GetType().InvokeMember( 
"InsertSectionTags",
BindingFlags.Default BindingFlags.InvokeMethod,
null,
model,
new object[]{});

That is ever so much nicer, I m sure you ll agree. But now, you see, we re only one short step away from what we really want. We can implement the Perform() method on TextModel quite easily, like this:

 private static object[] noArgs = {}; 
public void Perform(string methodName) {
this.GetType().InvokeMember(
methodName,
BindingFlags.Public BindingFlags.InvokeMethod BindingFlags.Instance,
null,
this,
noArgs);
}

Now frankly, I m pretty proud of this. I ve learned how to do Reflection ” that s what this is called ”well enough to send a message to an object, given only its name. I ve implemented a method on TextModel to do that fairly transparently , and I m all set now to eliminate the duplication that is coming real soon now.




Extreme Programming Adventures in C#
Javaв„ў EE 5 Tutorial, The (3rd Edition)
ISBN: 735619492
EAN: 2147483647
Year: 2006
Pages: 291

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net