SymbolExtensions.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using System.Linq.Expressions;
  2. using System.Reflection;
  3. using System;
  4. namespace Harmony
  5. {
  6. public static class SymbolExtensions
  7. {
  8. /// <summary>
  9. /// Given a lambda expression that calls a method, returns the method info.
  10. /// </summary>
  11. /// <typeparam name="T"></typeparam>
  12. /// <param name="expression">The expression.</param>
  13. /// <returns></returns>
  14. public static MethodInfo GetMethodInfo(Expression<Action> expression)
  15. {
  16. return GetMethodInfo((LambdaExpression)expression);
  17. }
  18. /// <summary>
  19. /// Given a lambda expression that calls a method, returns the method info.
  20. /// </summary>
  21. /// <typeparam name="T"></typeparam>
  22. /// <param name="expression">The expression.</param>
  23. /// <returns></returns>
  24. public static MethodInfo GetMethodInfo<T>(Expression<Action<T>> expression)
  25. {
  26. return GetMethodInfo((LambdaExpression)expression);
  27. }
  28. /// <summary>
  29. /// Given a lambda expression that calls a method, returns the method info.
  30. /// </summary>
  31. /// <typeparam name="T"></typeparam>
  32. /// <param name="expression">The expression.</param>
  33. /// <returns></returns>
  34. public static MethodInfo GetMethodInfo<T, TResult>(Expression<Func<T, TResult>> expression)
  35. {
  36. return GetMethodInfo((LambdaExpression)expression);
  37. }
  38. /// <summary>
  39. /// Given a lambda expression that calls a method, returns the method info.
  40. /// </summary>
  41. /// <param name="expression">The expression.</param>
  42. /// <returns></returns>
  43. public static MethodInfo GetMethodInfo(LambdaExpression expression)
  44. {
  45. var outermostExpression = expression.Body as MethodCallExpression;
  46. if (outermostExpression == null)
  47. throw new ArgumentException("Invalid Expression. Expression should consist of a Method call only.");
  48. var method = outermostExpression.Method;
  49. if (method == null)
  50. throw new Exception("Cannot find method for expression " + expression);
  51. return method;
  52. }
  53. }
  54. }