繁体   English   中英

扩展方法的反思

[英]reflection on an extension method

现在是两个小时,我正在尝试对扩展方法进行一些思考。 我想要的是称为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);

尝试:

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

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

我不确定为什么要在代码中使用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);

暂无
暂无

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

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