UPDATE: Here is a nice post that explains and provides a flexible utility method to access MethodInfos with refactor safe code. http://www.codeducky.org/10-utilities-c-developers-should-know-part-two/
I think Jon Skeet's answer is fine if you only want to cover void parameterless methods. A more general solution would look like this:
public class MyClass
{
public void UnitTestOne(int i) { /* impl */ }
public int UnitTestTwo() { /* impl */ }
public void UnitTestThree()
{
var methodCallExpressions = new Expression<Action<MyClass>>[] {
mc => mc.UnitTestOne(default(int)), //Note that a dummy argument is provided
mc => mc.UnitTestTwo()
};
var names = methodCallExpressions.Select(mce =>
((MethodCallExpression) mce.Body).Method.Name);
}
}
Note that we use an array of Expression<Action<MyClass>>
in order to make a list of method calls on MyClass
without knowing the return type and parameter types of each method call. Each method call expression is provided dummy variables to instantiate the expression.
Then the body of each expression is cast to a MethodCallExpression
which, as the type name indicates, holds an expression which is just the calling of a method. That type has a Method
property which is the MethodInfo
of the method being called.
In the link you provided, a property name is extracted similarly using a MemberExpression
. Using MethodCallExpression
makes the examples quite similar.
By the way, you can also use Expression<Action>
instead of Expression<Action<MyClass>>
if you prefer. Replace the methodCallExpressions
instantiation with:
var methodCallExpressions = new Expression<Action>[] {
() => this.UnitTestOne(default(int)),
() => this.UnitTestTwo()
};
I see this as mostly a stylistic decision, although it would also allow you to encapsulate method calls on a different class, using something like () => (new MyClass2()).UnitTestThree()
.