fork(3) download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Linq.Expressions;
  5. using System.Reflection;
  6. using System.Text;
  7.  
  8. namespace MyNamespace
  9. {
  10. public static class MethodSupport<T>
  11. {
  12. public static string ActionName(Expression<Func<T, Action>> expression)
  13. {
  14. return MethodName(expression);
  15. }
  16.  
  17. public static string ActionName<TParam>(Expression<Func<T, Action<TParam>>> expression)
  18. {
  19. return MethodName(expression);
  20. }
  21.  
  22. public static string FuncName<TResult>(Expression<Func<T, Func<TResult>>> expression)
  23. {
  24. return MethodName(expression);
  25. }
  26.  
  27. public static string FuncName<TParam, TResult>(Expression<Func<T, Func<TParam, TResult>>> expression)
  28. {
  29. return MethodName(expression);
  30. }
  31.  
  32. private static bool IsNET45 = Type.GetType("System.Reflection.ReflectionContext", false) != null;
  33.  
  34. public static string MethodName(LambdaExpression expression)
  35. {
  36. var unaryExpression = (UnaryExpression)expression.Body;
  37. var methodCallExpression = (MethodCallExpression)unaryExpression.Operand;
  38.  
  39. if (IsNET45)
  40. {
  41. var methodCallObject = (ConstantExpression)methodCallExpression.Object;
  42. var methodInfo = (MethodInfo)methodCallObject.Value;
  43. return methodInfo.Name;
  44. }
  45. else
  46. {
  47. var methodInfoExpression = (ConstantExpression)methodCallExpression.Arguments.Last();
  48. var methodInfo = (MemberInfo)methodInfoExpression.Value;
  49. return methodInfo.Name;
  50. }
  51.  
  52. }
  53. }
  54.  
  55. public class MyClass
  56. {
  57. public void Foo() { }
  58.  
  59. public void Fooz(int e) { }
  60.  
  61. public int Bar() { return 1; }
  62.  
  63. public int Barz(int c) { return 1; }
  64. }
  65.  
  66. public class Program
  67. {
  68.  
  69. public static void AssertAreEqual(string first, string second)
  70. {
  71. if (first != second)
  72. Console.WriteLine("{0} != {1}", first, second);
  73. else
  74. Console.WriteLine("{0} == {1}", first, second);
  75. }
  76.  
  77. public static void Main(string[] args)
  78. {
  79. AssertAreEqual("Foo", MethodSupport<MyClass>.ActionName(c => c.Foo));
  80.  
  81. AssertAreEqual("Fooz", MethodSupport<MyClass>.ActionName<int>(c => c.Fooz));
  82.  
  83. AssertAreEqual("Bar", MethodSupport<MyClass>.FuncName<int>(c => c.Bar));
  84.  
  85. AssertAreEqual("Barz", MethodSupport<MyClass>.FuncName<int, int>(c => c.Barz));
  86. }
  87. }
  88. }
  89.  
Success #stdin #stdout 0.04s 34040KB
stdin
Standard input is empty
stdout
Foo == Foo
Fooz == Fooz
Bar == Bar
Barz == Barz