Moq and reflection, passing dynamically generated expression tree / lambda to moq

为君一笑 提交于 2019-12-05 22:02:22

Ok, this is possible, here is the corrected code.

// Create input parameter for lambda 
ParameterExpression value = Expression.Parameter(typeof(IFoo), "value"); 

// create return statement for lambda 
Expression setupProperty = Expression.Property(value, "Bar"); 

// convert expression to lambda (should now be the equivalent of "v => v.Bar") 
var func = Expression.Lambda<Func<IFoo, string>>(setupProperty, value);

var mockFoo = new Mock<IFoo>(); 
mockFoo.SetupProperty(func); // this works now
mockFoo.Object.Bar = "Burge+"; 

I investigated this by creating an expression from a lambda using the code below

Expression<Func<IFoo, string>> setupBar = v => c.Bar;

I then looked at this in the debugger in vs 2010. Expressions have a "Debug View" that shows a text representation of the expression so it is possible to add a watch on that or something similar. The above comes out as

 .Lambda #Lambda1<System.Func`2[WindowsFormsApplication1.IFoo,System.String]>(WindowsFormsApplication1.IFoo
 $v) {
   $v.Bar
 }

I looked at this and tried to work out what Expressions would make this, then created an expression and compared it in the debugger.

The interesting thing for me is that although this expression returns a value there is no assignment or return statement. I guess this must be implicit somehow.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!