2016-04-21 56 views
2

我試圖創建表達式,但失敗。如何手動構建將始終返回true的表達式?

我想建立類似Expression<Func<typeof(type), bool>> expression = _ => true;

我嘗試:

private static Expression GetTrueExpression(Type type) 
{ 
    LabelTarget returnTarget = Expression.Label(typeof(bool)); 
    ParameterExpression parameter = Expression.Parameter(type, "x"); 

    var resultExpression = 
     Expression.Return(returnTarget, Expression.Constant(true), typeof(bool)); 

    var delegateType = typeof(Func<,>).MakeGenericType(type, typeof(bool)); 

    return Expression.Lambda(delegateType, resultExpression, parameter); ; 
} 

用法:

var predicate = Expression.Lambda(GetTrueExpression(typeof(bool))).Compile(); 

但我得到的錯誤:Cannot jump to undefined label ''

+0

您可以嘗試使用'PredicateBuilder'由阿爾巴哈利兄弟。 'var'expr = PredicateBuilder.True ();'http://www.albahari.com/nutshell/predicatebuilder.aspx – willaien

+0

'typeof(type)'in your expression will * always * return'Type' – maksymiuk

+0

This works too: '公共靜態表達式GetTrueExpression ()=> Expression >)(x => true); var predicate = GetTrueExpression ();' –

回答

7

由於SIMP le如下:

private static Expression GetTrueExpression(Type type) 
{ 
    return Expression.Lambda(Expression.Constant(true), Expression.Parameter(type, "_")); 
}