簡體   English   中英

類型“System.Func`2[T,System.Boolean]”的表達式不能用於返回類型“System.Boolean”

[英]Expression of type 'System.Func`2[T,System.Boolean]' cannot be used for return type 'System.Boolean'

嗨,我在將我的 Expression 轉換為Expression<Func<T, bool>>遇到問題。 這可能嗎? Expression.Lambda 調用錯誤Expression of type 'System.Func`2[T,System.Boolean]' cannot be used for return type 'System.Boolean' ,這對我來說沒有意義,因為我認為定義函數具有匹配的返回類型?

Expression expression = serializer.DeserializeText(serializedText);
ParameterExpression entityType = Expression.Parameter(typeof(T));
Expression<Func<T, bool>> typedExpression = Expression.Lambda<Func<T, bool>>(expression, entityType);

編輯:表達式是一個強類型的 lambda,例如 s => idArray.Contains(s.SomeIntColumn),其中 s 是類型 T。然后使用 LINQ 序列化器序列化表達式,然后反序列化為 System.Linq.Expression。 因為我知道它是一個帶有 return bool 的 T 類型的函數,所以我想強烈地輸入它。

不確定您的代碼段中的serializedText是什么,但只要它是一個返回booleanLambdaExpression ,您就應該能夠執行以下操作。

  Expression expression = Expression.Lambda(Expression.Constant(true), Expression.Parameter(typeof(string)));

  Expression<Func<string, bool>> typedExpression = (Expression<Func<string, bool>>)(expression);

  Console.WriteLine(typedExpression.Compile().Invoke("Hello"));

用您的通用類型替換string

在您的示例中,如果可以將serializedText反序列化為Expression則以下應該可以工作,您將不得不更改它以供考慮。

Expression<Func<T, bool>> typedExpression = (Expression<Func<T, bool>>)Expression.Lambda(
                                                                        serializer.DeserializeText(serializedText), 
                                                                        Expression.Parameter(typeof(T)));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM