1. 程式人生 > >Util應用程式框架公共操作類(十二):Lambda表示式公共操作類(三)

Util應用程式框架公共操作類(十二):Lambda表示式公共操作類(三)

     /// <summary> /// 獲取值,範例:t => t.Name == "A",返回 A /// </summary> /// <param name="expression">表示式,範例:t => t.Name == "A"</param> public static object GetValue( Expression expression ) { if ( expression == null ) return
null; switch ( expression.NodeType ) { case ExpressionType.Lambda: return GetValue( ( (LambdaExpression)expression ).Body ); case ExpressionType.Convert: return GetValue( ( (UnaryExpression)expression ).Operand );
case ExpressionType.Equal: case ExpressionType.NotEqual: case ExpressionType.GreaterThan: case ExpressionType.LessThan: case ExpressionType.GreaterThanOrEqual: case ExpressionType.LessThanOrEqual:
return GetValue( ( (BinaryExpression)expression ).Right ); case ExpressionType.Call: return GetValue( ( (MethodCallExpression)expression ).Arguments.FirstOrDefault() ); case ExpressionType.MemberAccess: return GetMemberValue( (MemberExpression)expression ); case ExpressionType.Constant: return GetConstantExpressionValue( expression ); } return null; } /// <summary> /// 獲取屬性表示式的值 /// </summary> private static object GetMemberValue( MemberExpression expression ) { if ( expression == null ) return null; var field = expression.Member as FieldInfo; if ( field != null ) { var constValue = GetConstantExpressionValue( expression.Expression ); return field.GetValue( constValue ); } var property = expression.Member as PropertyInfo; if ( property == null ) return null; var value = GetMemberValue( expression.Expression as MemberExpression ); return property.GetValue( value ); } /// <summary> /// 獲取常量表達式的值 /// </summary> private static object GetConstantExpressionValue( Expression expression ) { var constantExpression = (ConstantExpression)expression; return constantExpression.Value; }