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
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