What the various ways of calling a method at runtime?
I need to call a method on an object but I do not know the method name until runtime.
What are the techniques available?
(e.g. GetMethod().Invoke(), deleg开发者_运维百科ates, c# 4.0 dynamic)
Thanks!
The C# 4.0 dynamic
functionality is going to be the easiest way to do this. In a very real sense, dynamic
is "just a wrapper" around Reflection. It's a very good wrapper, though, that is probably your best option.
Other ways, in approximately increasing level of difficult:
- Using a third-party Reflection library. Not sure what's out there these days.
- Writing your own Reflection code.
- Use the CodeDOM to create code that calls the method you want to call.
- Emit IL that does pretty much the same thing as the CodeDOM generated code.
- Create C# source code that you then compile into an assembly that you can call, which in turn calls the desired method.
The last three are not for the faint of heart. Your best bet is to use dynamic
or write your own Reflection code. If I had had dynamic
three years ago when I was writing code for something similar, I would have used it.
You can use Reflection to call functions that you do not know the name of until run time. Here's some doc:
http://msdn.microsoft.com/en-us/library/f7ykdhsy%28VS.80%29.aspx
精彩评论