创建一个表达式来; Func键<,>>使用反射 [英] Create an Expression<Func<,>> using reflection

查看:235
本文介绍了创建一个表达式来; Func键<,>>使用反射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用起订量来创建一个数据集的嘲笑林。

Im using Moq to create mocks of a data set.

我创建了一个小帮手类,允许我在内存中存储有一个,而不是数据库的那做单元测试轻而易举。这样我可以添加和删除我的模拟数据组项目,这让我来测试我的插入和删除服务呼叫。

I have created a little helper class that allows me to have an in memory storage instead of a database that makes unit testing a breeze. That way I can add and remove items from my mock data set, this allows me to test my insert and delete service calls.

在模拟的设置我有一个线,看起来像以下

During the setup of the mock I have a line that looks like the following

this.Setup(i => i.AcademicCycles).Returns(mockStore.GetList<AcademicCycle>());



我假装有很多的属性,所以我想执行使用反射此设置步骤。我已成功地在返回的过程中通过反射工作的一部分,但我被困在拉姆达方法设置

My mock has a lot of properties so I would like to perform this setup step using reflection. I have managed to the Returns part of the process working via reflection but I am stuck on the lambda method to Setup.

设置需要一个

表达式来; Func键< GoalsModelUnitOfWork,IQueryable的< AcademicCycle>>> 对应于 I => i.AcademicCycles

和我想动态地创建这一点。使用反射我有以下几点:

and I would like to create this dynamically. Using reflection I have the following:

属性的名称:AcademicCycles

The name of the property: "AcademicCycles"

键入的IQueryable< AcademicCycle>

键入 AcademicCycle

我也有 I 中拉姆达声明这是实例的 GoalsModelUnitOfWork

I also have the instance of the i in the lambda statement which is a GoalsModelUnitOfWork

推荐答案

中的代码创建表达式动态会是这样:

The code to create the expression dynamically would be like this:

ParameterExpression parameter = Expression.Parameter(typeof (GoalsModelUnitOfWork), "i");
MemberExpression property = Expression.Property(parameter, "AcademicCycles");

var queryableType = typeof (IQueryable<>).MakeGenericType(typeof (AcademicCycle));
var delegateType = typeof (Func<,>).MakeGenericType(typeof (GoalsModelUnitOfWork), queryableType);

var yourExpression = Expression.Lambda(delegateType, property, parameter);



结果将有需要的类型,但问题是,返回类型 Expression.Lambda() LambdaExpression ,你不能到表达式来; Func键< ;. ..>> 将它传递作为参数传递给你的设置功能,因为你不知道的函数功能泛型类型参数。所以,你必须调用设置方法,通过反射太:

The result will have the desired type, but the problem is that the return type of Expression.Lambda() is LambdaExpression and you can't perform a type cast to Expression<Func<...>> to pass it as parameter to your setup function because you don't know the generic type parameters for the Func. So you have to invoke the Setup method by reflection, too:

this.GetType().GetMethod("Setup", yourExpression.GetType()).Invoke(this, yourExpression);

这篇关于创建一个表达式来; Func键&LT;,&GT;&GT;使用反射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆