ERROR Static method requires a null instance, non-static method requires a non-empty instance

I am trying to create an expression tree. I need to read data from a data table and check its columns. Checked columns, as well as the number of checked columns, are known only at runtime. The column names are given to me as a string array, and each column has a list of rows to be checked. I tried out expression tree patterns as shown below.

Here I come across an error.

A static method requires a null instance; a non-static method requires a non-empty instance. Parameter Name: Instance

in line

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

Please help me!

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 })); 
+6
source share
1 answer

This means that the call to the method you are trying to represent is static, but you give it the target expression. This is like trying to call:

 Thread t = new Thread(...); // Invalid! t.Sleep(1000); 

You are just trying to do this in the form of an expression tree, and this is also forbidden.

This seems to be happening for the Field extension method on DataRowExtensions - so the "target" of the extension method should be expressed as the first argument to be called, because you really want to call:

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

So you want:

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

This will cause this overload , which is a way to invoke a static method with two arguments.

+9
source

Source: https://habr.com/ru/post/899850/


All Articles