/// <summary> /// True if expression belongs to a lambda argument (expression parameter) /// </summary> /// <param name="node"></param> /// <param name="type"></param> /// <returns></returns> public static bool BelongsToParameter(this Expression node, Type type = null) { node.MustNotBeNull(); Expression parent = null; switch (node.NodeType) { case ExpressionType.MemberAccess: parent = node.CastAs <MemberExpression>().Expression; break; case ExpressionType.Call: var m = node.CastAs <MethodCallExpression>(); parent = m.Object; if (m.HasParameterArgument(type)) { return(true); } break; case ExpressionType.NewArrayInit: var n = node as NewArrayExpression; return(n.Expressions.Any(e => e.BelongsToParameter(type))); case ExpressionType.Not: case ExpressionType.Convert: var u = node as UnaryExpression; parent = u.Operand; break; } if (parent == null) { return(false); } if (parent.NodeType != ExpressionType.Parameter) { return(parent.BelongsToParameter(type)); } if (type != null) { if (parent.Type != type) { return(false); } } return(true); }
/// <summary> /// Gets the value of an expresion if it's a property,field,constant or method call /// </summary> /// <exception cref="InvalidOperationException"></exception> /// <param name="node"></param> /// <returns></returns> public static object GetValue(this Expression node) { node.MustNotBeNull(); switch (node.NodeType) { case ExpressionType.Convert: return(GetConvertValue(node.CastAs <UnaryExpression>())); case ExpressionType.Constant: return(node.CastAs <ConstantExpression>().Value); case ExpressionType.New: return(node.CastAs <NewExpression>().CreateObject()); case ExpressionType.MemberInit: return(node.CastAs <MemberInitExpression>().GetValue()); case ExpressionType.NewArrayInit: return(node.CastAs <NewArrayExpression>().CreateArray()); case ExpressionType.MemberAccess: return(node.CastAs <MemberExpression>().GetValue()); case ExpressionType.ArrayIndex: return(GetArrayIndex(node.CastAs <BinaryExpression>())); case ExpressionType.Call: return(node.CastAs <MethodCallExpression>().GetValue()); } throw new InvalidOperationException("You can get the value of a property,field,constant or method call"); }
/// <summary> /// True if expresion belongs to a parameter or is a method which has a parameter argument. /// Doesn't handle lambdas /// </summary> /// <param name="node"></param> /// <param name="type"></param> /// <returns></returns> public static bool InvolvesParameter(this Expression node, Type type = null) { node.MustNotBeNull(); if (node.IsParameter(type) || node.BelongsToParameter(type)) { return(true); } if (node.NodeType == ExpressionType.Call) { return(node.CastAs <MethodCallExpression>().HasParameterArgument(type)); } if (node.NodeType == ExpressionType.New) { return(node.CastAs <NewExpression>().HasParameterArgument(type)); } if (node.NodeType == ExpressionType.NewArrayInit) { return(node.CastAs <NewArrayExpression>().Expressions.Any(e => e.BelongsToParameter(type))); } return(false); }