简体   繁体   English

扩展方法的反思

[英]reflection on an extension method

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. 我想要的是称为DataRow的通用静态方法“ Field”,但我没有成功。 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);

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 . static方法上使用Expression.Call时,第一个参数应作为null传递。 The instance is actually a parameter. 该实例实际上是一个参数。

I am not sure why you are using Expression in your code, but for simple stuffs the following code works. 我不确定为什么要在代码中使用Expression,但是对于简单的东西,以下代码可以工作。 It just invokes the method Field on class DataRowExtensions using Reflection. 它仅使用反射在类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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM