静态方法需要空实例,非静态方法需要非空实例。

8
我正在尝试创建一个表达式树。我需要从数据表中读取数据并检查其列。要检查的列以及要检查的列数仅在运行时才知道。列名以字符串数组的形式给出,每个列都有一个要检查的字符串列表。我尝试了一些示例表达式树,例如下面的代码。

在这里我遇到了一个错误。

静态方法需要空实例,非静态方法需要非空实例。 参数名称: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 }));
1个回答

10
这意味着你试图表示的方法调用是静态的,但你却给它一个目标表达式。这就像试图调用:
Thread t = new Thread(...);
// Invalid!
t.Sleep(1000);

您似乎试图以表达式树形式完成此操作,但这也是不允许的。

看起来这是发生在DataRowExtensions上的Field扩展方法 - 因此,扩展方法的“目标”需要作为调用的第一个参数表达,因为您实际上要调用:

DataRowExtensions.Field<T>(row, col);

那么你想要:

inner = Expression.Call(mi, rowexp, colexp);

这将调用 此重载,这是调用带有两个参数的静态方法的方式。


你能否详细解释一下上面的内容?为什么在这里将方法信息作为 Expression.Call 方法的第一个参数传递? - Kobojunkie
@Kobojunkie:因为这是告诉Expression.Call我们感兴趣的静态方法的方式。请参见http://msdn.microsoft.com/en-us/library/bb301084.aspx。 - Jon Skeet

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接