簡體   English   中英

如何在System.Linq.Expression C#中初始化Expression.Call對象

[英]How to initialize the Expression.Call object in System.Linq.Expression C#

我想在if else條件之外初始化Expression Call。 因為我必須使用它來生成表達式主體,因為我有兩個來自數據庫的不同類型,即int和int?。 我的代碼如下。 我在實例化toString對象時遇到錯誤。

 var parameterExp = Expression.Parameter(typeof(T), "type");
 var propertyExp = Expression.Property(parameterExp, propertyName);
 MethodInfo method = typeof(string).GetMethod(methodType, new[] { typeof(string) });
 var searchValue = Expression.Constant(propertyValue.ToLower(), typeof(string));

var toString = new MethodCallExpression();

if (propertyName == nameof(CustomerListDto.Id))
{
     toString = Expression.Call(propertyExp, typeof(int).GetMethod("ToString", System.Type.EmptyTypes));
}
else
{
    toString = Expression.Call(propertyExp, typeof(int?).GetMethod("ToString", System.Type.EmptyTypes));
}

var body = Expression.Call(toString, method, searchValue);
return Expression.Lambda<Func<T, bool>>(body, parameterExp);

我不知道如何初始化ExpressionCall。 這是我想知道的事情。 當前,它給我錯誤“ MethodCallExpression不包含采用0參數的構造函數”。 我進行了很多搜索,但找不到任何解決方案。

由於構造函數是私有的,因此無法手動實例化MethodCallExpression。 您可以獲取MethodCallExpression的實例作為Expression.Call的返回值。 您可能只想聲明為

MethodCallExpression toString;

// Then assign it with Expression.Call(...);

if (propertyName == nameof(CustomerListDto.Id))
{
     toString = Expression.Call(propertyExp, typeof(int).GetMethod("ToString", System.Type.EmptyTypes));
}
else
{
    toString = Expression.Call(propertyExp, typeof(int?).GetMethod("ToString", System.Type.EmptyTypes));
}

暫無
暫無

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

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