开发者

Defining a C# Method Body at runtime (dynamically)

I have a base class that defines (among others) a certain empty virtual method (used as an event handler).

Up to now, all i开发者_StackOverflow中文版nstances are created from a derived type, which overrides the virtual method to fill it with life. This type is generated dynamically and does all it should, but I really wonder whether Reflection (.Emit) or whatever levers the .Net framework has to offer make it possible to just modify the body of the abovementioned method.

Any ideas?

Thanks in advance!


You could make the body call a delegate and then change the delegate instead of making the method virtual and overriding it.

And if the only use of that method is as event handler, why make it a method at all? Just assign the generated function directly to the eventhandler.

You can construct an Expression Tree and then compile it into a delegate which you can then assign to the eventhandler.


Rather than try to fill in a method body, why don't you just pass a delegate to the constructor? It's relatively easy to build up delegates dynamically (e.g. with DynamicMethod.CreateDelegate), and then you don't need to worry about modifying existing types.


As far as I know, it is forbidden to alter existing code after it was compiled. You can dynamically add new pieces of code, but are not allowed to change existing one and that applies both to compiled commands and definitions of classes or other data types.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜