【问题标题】:reflection on an extension method对扩展方法的反思
【发布时间】:2014-12-01 13:39:57
【问题描述】:

现在是两个小时,我正在尝试对扩展方法进行一些思考。 我想要的是调用 DataRow 的名为“Field”的通用静态方法,但我没有成功。 谁能帮帮我?

这是我的代码:

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);

【问题讨论】:

标签: c# linq reflection datatable extension-methods


【解决方案1】:

试试:

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

static 方法上使用Expression.Call 时,第一个参数应作为null 传递。实例实际上是一个参数。

【讨论】:

    【解决方案2】:

    我不确定您为什么在代码中使用 Expression,但是对于简单的东西,以下代码可以工作。它只是使用反射调用 DataRowExtensions 类的方法 Field。

     //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);
    

    【讨论】:

    • 实际上我需要将方法作为参数传递给通过反射轮流调用的数据表的“Where”方法。是否还有其他使用“表达式树”的解决方案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-08
    • 2011-05-31
    • 1970-01-01
    相关资源
    最近更新 更多