Can I get a reference to a method through reflection?

J

Joel

I need to get a reference to a method in my currently running class by the
method name. I don't want a MethodInfo object; I want an actual reference to
the method. Basically I'm trying to programatically load a delegate via the
method name that should be invoked. For example the "normal" way of doing it
is:

internal delegate void MyDelegate(DataSet ds); //delcare my delegate
....
MyDelegate d=new MyDelegate(MyFunc); //MyFunc is declared elsewhere as
"private void MyFunc(DataSet ds)"

What I want to do is:

internal delegate void MyDelegate(DataSet ds); //delcare my delegate
...
string str="MyFunc";
object obj=GET_METHOD_REFERENCE(str); //this is what I don't know how
to do
MyDelegate d=new MyDelegate(obj);

It seems that refelection should be able to handle that but I can't find
anything.

TIA
</joel>
 
J

Jon Skeet [C# MVP]

Joel said:
I need to get a reference to a method in my currently running class by the
method name. I don't want a MethodInfo object; I want an actual reference to
the method.

There's no such thing.
Basically I'm trying to programatically load a delegate via the
method name that should be invoked. For example the "normal" way of doing it
is:

internal delegate void MyDelegate(DataSet ds); //delcare my delegate
....
MyDelegate d=new MyDelegate(MyFunc); //MyFunc is declared elsewhere as
"private void MyFunc(DataSet ds)"

What I want to do is:

internal delegate void MyDelegate(DataSet ds); //delcare my delegate
...
string str="MyFunc";
object obj=GET_METHOD_REFERENCE(str); //this is what I don't know how
to do
MyDelegate d=new MyDelegate(obj);

It seems that refelection should be able to handle that but I can't find
anything.

I suggest you use

MyDelegate d = (MyDelegate)Delegate.CreateDelegate
(typeof(MyDelegate), mi);

where mi is the appropriate MethodInfo reference (obtained in the usual
manner).
 
J

Joel Wilson

Jon,

Thanks, that's precisely what I was looking for although I used

MyDelegate d=(MyDelegate)Delegate.CreateDelegate(typeof(MyDelegate),
this, "MyMethod");

since I needed a non-static delegate.

Thanks!!!

</joel>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top