现在已经两个小时了,我正在尝试对一个扩展方法进行一些思考。我想要的是调用DataRow的名为“字段”的通用静态方法,但我没有成功。有人能帮我吗?
下面是我的代码:
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);发布于 2014-12-01 22:02:17
尝试:
Expression left = Expression.Call(null, gx, pe, Expression.Constant(TwoParts[0]));在static方法上使用Expression.Call时,第一个参数应作为null传递。实例实际上是一个参数。
发布于 2014-12-01 22:11:22
我不确定你为什么要在你的代码中使用表达式,但是对于简单的东西,下面的代码是有效的。它只是使用反射调用类DataRowExtensions上的方法字段。
//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);https://stackoverflow.com/questions/27229695
复制相似问题