Generate Multiple methods using Reflection
I would like to know how I can generate multiple type methods using Reflection. Example :
class A() {
public void CoreMethod1() {
}
public void CoreMethod2() {
}
// .. 20 such core methods
public void Method1() {
//some initializations
//call to CoreMethod1();
}
public void Method2() {
//some initializations
//call to CoreMethod2();
}
// i need 20 such methods which will call their respective CoreMethods
//Method1(),Method2() are similar except for their call to the core method. i.e Every respective method will call its coremethod. Ex : Method1() -> CoreMethod1(), Method2() -> CoreMethod2()
}
My question, can I generate Method1(), Method2(), Method3().. dynamically to c开发者_运维问答all their respective core methods. Is there a better way to get this done ?
Probably worth looking into one of IL rewriting libraries:
- Automapper http://automapper.codeplex.com/
- LinFu http://code.google.com/p/linfu/
- PostSharp http://www.sharpcrafters.com/
If you can't work out how to make one of those work for you, have a look at manual Reflection.Emit
. This codeproject article is probably the most detailed source doing it.
Write a simple code-generator using T4 templates. Here are some good resources.
- http://www.olegsych.com/2008/09/t4-tutorial-creatating-your-first-code-generator/
- http://www.hanselman.com/blog/T4TextTemplateTransformationToolkitCodeGenerationBestKeptVisualStudioSecret.aspx
- http://msdn.microsoft.com/en-us/vstudio/cc308634.aspx
- http://www.pnpguidance.net/Screencast/T4TemplatesVisualStudioCodeGenerationScreencast.aspx
精彩评论