Reputation: 1
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);
Upvotes: 0
Views: 507
Reputation: 109
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);
Upvotes: 0
Reputation: 1063864
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.
Upvotes: 1