Can I get a reference to a method through reflection?

  • Thread starter Thread starter Joel
  • Start date Start date
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>
 
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).
 
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>
 
Back
Top