Reflection - there must be a way!

T

Tim Smith

I need to get a method name from a class, as a string, without
hardcoding a string.

I have ended up with a generic method for execution, which needs a
method name and an (optional) array of parameters

private object Execute (object instance, string methodName, params
object[] parameters) {
// preamble

// written from memory, may have minor typos
object returnValue =
instance.GetType().GetMethod(methodName).Invoke(instance, parameters);

// postamble
return returnValue;
}

My calling method is along these lines

public void DoSomething() {
Execute(this, "MyMethod", param1, param2);
}

I do NOT want to hard code the method name, since typos cannot be
identified at compile time.

The best, and it is not 'good' I could do was the following

private delegate object myDelegateForExecute (param1, param2);
// then replace with
public void DoSomething() {
Execute(this, new MyDelegate(this.DoSomething).Method.Name, param1,
param2);
}

But that seems very ugly, surely there MUST be a way of transforming

this.DoSomething into "DoSomething"

but I cannot find it...

tia

Tim
 
T

Tim Smith

No, that would only return the name of the current method, I need the
string name of a different (helper) method defined in the class.


Kimmo Laine said:
Try

using System.Reflection;

Methodbase.GetCurrentMethod()



- kl


Tim Smith said:
I need to get a method name from a class, as a string, without
hardcoding a string.

I have ended up with a generic method for execution, which needs a
method name and an (optional) array of parameters

private object Execute (object instance, string methodName, params
object[] parameters) {
// preamble

// written from memory, may have minor typos
object returnValue =
instance.GetType().GetMethod(methodName).Invoke(instance, parameters);

// postamble
return returnValue;
}

My calling method is along these lines

public void DoSomething() {
Execute(this, "MyMethod", param1, param2);
}

I do NOT want to hard code the method name, since typos cannot be
identified at compile time.

The best, and it is not 'good' I could do was the following

private delegate object myDelegateForExecute (param1, param2);
// then replace with
public void DoSomething() {
Execute(this, new MyDelegate(this.DoSomething).Method.Name, param1,
param2);
}

But that seems very ugly, surely there MUST be a way of transforming

this.DoSomething into "DoSomething"

but I cannot find it...

tia

Tim
 

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