0

this is two hour now that i am trying to make some reflection on an extention method. what i want is call the generic static method called "Field" of DataRow and i didn't sucess. Can anyone help me ?

Here's my code :

ParameterExpression pe = Expression.Parameter(typeof(DataRow), "field");
var x = typeof(DataRowExtensions).GetMethod(
    "Field", 
    new Type[]{typeof(DataRow),typeof(string)});                               
var gx = x.MakeGenericMethod(typeof(DataRow));
var y = new[] { Expression.Constant(TwoParts[0]) };
Expression left = Expression.Call(pe, gx, y);
Expression right = Expression.Constant(val.Remove(0, 1));
var w = e1 = Expression.NotEqual(left, right);
juharr
  • 31,741
  • 4
  • 58
  • 93
We0orad
  • 1
  • 1
  • possible duplicate of [How do I invoke an extension method using reflection?](http://stackoverflow.com/questions/1452261/how-do-i-invoke-an-extension-method-using-reflection) – pmcoltrane Dec 01 '14 at 13:52
  • I already saw this answer, but it does not match what i need. Actually, i want to make an expression call to use it with linq. not invoke the static method independently. – We0orad Dec 01 '14 at 14:02

2 Answers2

1

Try:

Expression left = Expression.Call(null, gx, pe, Expression.Constant(TwoParts[0]));

When using Expression.Call on a static method, the first parameter should passed as null. The instance is actually a parameter.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

I am not sure why you are using Expression in your code, but for simple stuffs the following code works. It just invokes the method Field on class DataRowExtensions using Reflection.

 //creating a fake table, use the one you have
            DataTable fakeTable = new DataTable();
            fakeTable.Columns.Add(new DataColumn("Name",typeof(string)));
            fakeTable.Rows.Add(new object[]{"John Doe"});
            DataRow r= fakeTable.Rows[0];

            //change to the type of the field you want to retrieve from the data row
            var myType = typeof(string);
            //change to the column name you want retrieve from the data row
            var columnName = "Name";

            //getting the extensor method T DataRowExtensions.Field<T>(this DataRow dr,string columnName)
            MethodInfo genericMethod = typeof(DataRowExtensions).GetMethod("Field", new Type[] { typeof(DataRow), typeof(string) });
            MethodInfo method = genericMethod.MakeGenericMethod(myType);
            //as the extensor method is static, instance is not need so just pass null
            var result = method.Invoke(null,new object[]{ r, columnName});

            Console.WriteLine(result);
Raimil Cruz
  • 109
  • 1
  • 7
  • actually i need to pass, as parameter, the method to "Where" of a datatable wich called in turns by reflection. is still there any other solution using "Expression Tree" – We0orad Dec 01 '14 at 15:17