Created
May 16, 2014 06:38
-
-
Save forcewake/3912cc65b88f3d355d16 to your computer and use it in GitHub Desktop.
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
namespace Framework.Jobs.Arguments | |
{ | |
using System; | |
using System.Linq.Expressions; | |
public static class StaticReflection | |
{ | |
public static string GetMemberName<T>( | |
this T instance, | |
Expression<Func<T, object>> expression) | |
{ | |
return GetMemberName(expression); | |
} | |
public static string GetMemberName<T>( | |
Expression<Func<T, object>> expression) | |
{ | |
if (expression == null) | |
{ | |
throw new ArgumentException( | |
"The expression cannot be null."); | |
} | |
return GetMemberName(expression.Body); | |
} | |
public static string GetMemberName<T>( | |
this T instance, | |
Expression<Action<T>> expression) | |
{ | |
return GetMemberName(expression); | |
} | |
public static string GetMemberName<T>( | |
Expression<Action<T>> expression) | |
{ | |
if (expression == null) | |
{ | |
throw new ArgumentException( | |
"The expression cannot be null."); | |
} | |
return GetMemberName(expression.Body); | |
} | |
private static string GetMemberName( | |
Expression expression) | |
{ | |
if (expression == null) | |
{ | |
throw new ArgumentException( | |
"The expression cannot be null."); | |
} | |
if (expression is MemberExpression) | |
{ | |
// Reference type property or field | |
var memberExpression = | |
(MemberExpression) expression; | |
return memberExpression.Member.Name; | |
} | |
if (expression is MethodCallExpression) | |
{ | |
// Reference type method | |
var methodCallExpression = | |
(MethodCallExpression) expression; | |
return methodCallExpression.Method.Name; | |
} | |
if (expression is UnaryExpression) | |
{ | |
// Property, field of method returning value type | |
var unaryExpression = (UnaryExpression) expression; | |
return GetMemberName(unaryExpression); | |
} | |
throw new ArgumentException("Invalid expression"); | |
} | |
private static string GetMemberName( | |
UnaryExpression unaryExpression) | |
{ | |
if (unaryExpression.Operand is MethodCallExpression) | |
{ | |
var methodExpression = | |
(MethodCallExpression) unaryExpression.Operand; | |
return methodExpression.Method.Name; | |
} | |
return ((MemberExpression) unaryExpression.Operand) | |
.Member.Name; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment