Created
April 4, 2011 09:08
-
-
Save duncansmart/901329 to your computer and use it in GitHub Desktop.
Type-safe GetMethod: get a MethodInfo without a magic string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Reflection; | |
using System.Linq.Expressions; | |
class ExpressionUtil | |
{ | |
// Returns the MethodInfo of the given lambda. Use instead of Type.GetMethod("name", paramTypes). | |
public static MethodInfo GetMethod<T>(Expression<Action<T>> lambda) | |
{ | |
var call = lambda.Body as MethodCallExpression; | |
if (call == null) | |
throw new ArgumentException("Expression body was expected to be a method call, but was '" + lambda.Body + "' (" + call.GetType() + ")"); | |
return call.Method; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment