首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >关于扩展方法的思考

关于扩展方法的思考
EN

Stack Overflow用户
提问于 2014-12-01 21:39:57
回答 2查看 493关注 0票数 0

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

下面是我的代码:

代码语言:javascript
复制
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);
EN

回答 2

Stack Overflow用户

发布于 2014-12-01 22:02:17

尝试:

代码语言:javascript
复制
Expression left = Expression.Call(null, gx, pe, Expression.Constant(TwoParts[0]));

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

票数 1
EN

Stack Overflow用户

发布于 2014-12-01 22:11:22

我不确定你为什么要在你的代码中使用表达式,但是对于简单的东西,下面的代码是有效的。它只是使用反射调用类DataRowExtensions上的方法字段。

代码语言:javascript
复制
 //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);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27229695

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档