using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
using System.Reflection;
namespace AutoLoL.Logic.Utils
{
public static class TypeManager
{
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public static PropertyInfo GetProperty(Expression> propertySelector)
{
Expression expression = propertySelector.Body;
// If the Property returns a ValueType then a Convert is required => Remove it
if (expression.NodeType == ExpressionType.Convert || expression.NodeType == ExpressionType.ConvertChecked)
{
expression = ((UnaryExpression)expression).Operand;
}
// If this isn't a member access expression then the expression isn't valid
MemberExpression memberExpression = expression as MemberExpression;
if (memberExpression == null)
{
ThrowExpressionArgumentException("propertySelector");
}
expression = memberExpression.Expression;
// If the Property returns a ValueType then a Convert is required => Remove it
if (expression.NodeType == ExpressionType.Convert || expression.NodeType == ExpressionType.ConvertChecked)
{
expression = ((UnaryExpression)expression).Operand;
}
// Check if the expression is the parameter itself
if (expression.NodeType != ExpressionType.Parameter)
{
ThrowExpressionArgumentException("propertySelector");
}
// Finally retrieve the MemberInfo
PropertyInfo propertyInfo = memberExpression.Member as PropertyInfo;
if (propertyInfo == null)
{
ThrowExpressionArgumentException("propertySelector");
}
return propertyInfo;
}
private static void ThrowExpressionArgumentException(string argumentName)
{
throw new ArgumentException("It's just the simple expression 'x => x.Property' allowed.", argumentName);
}
}
}