我正在尝试创建一个表达式树。我需要从数据表中读取数据并检查其列。要检查的列以及要检查的列数仅在运行时才知道。列名以字符串数组的形式给出,每个列都有一个要检查的字符串列表。我尝试了一些示例表达式树,例如下面的代码。
在这里我遇到了一个错误。
静态方法需要空实例,非静态方法需要非空实例。 参数名称:instance
在以下这一行:
inner = Expression.Call(rowexp,mi, colexp);
请帮我解决这个问题!!!
IQueryable<DataRow> queryableData = CapacityTable
.AsEnumerable()
.AsQueryable()
.Where(row2 => values.Contains(row2.Field<string>("Head1").ToString())
&& values.Contains(row2.Field<string>("Head2").ToString()));
MethodInfo mi = typeof(DataRowExtensions).GetMethod(
"Field",
new Type[] { typeof(DataRow),typeof(string) });
mi = mi.MakeGenericMethod(typeof(string));
ParameterExpression rowexp = Expression.Parameter(typeof(DataRow), "row");
ParameterExpression valuesexp = Expression.Parameter(typeof(List<string>), "values");
ParameterExpression fexp = Expression.Parameter(typeof(List<string>), "types");
Expression inner, outer, predicateBody = null;
foreach (var col in types)
{
// DataRow row = CapacityTable.Rows[1];
ParameterExpression colexp = Expression.Parameter(typeof(string), "col");
// Expression left = Expression.Call(pe, typeof(string).GetMethod("ToLower", System.Type.EmptyTypes));
inner = Expression.Call(rowexp,mi, colexp);
outer = Expression.Call(valuesexp, typeof(List<string>).GetMethod("Contains"), inner);
predicateBody = Expression.And(predicateBody,outer);
}
MethodCallExpression whereCallExpression = Expression.Call(
typeof(Queryable),
"Where",
new Type[] { queryableData.ElementType },
queryableData.Expression,
Expression.Lambda<Func<DataRow,bool>>(predicateBody, new ParameterExpression[] { rowexp }));
Expression.Call
我们感兴趣的静态方法的方式。请参见http://msdn.microsoft.com/en-us/library/bb301084.aspx。 - Jon Skeet