如何指定由一名前pression树方法返回的对象? [英] How do I specify the object to return from an expression tree method?
问题描述
我试图创建使用EX pression树,返回一个对象的方法,但我想不出如何实际指定返回对象。我试着读<一href="http://blogs.msdn.com/b/csharpfaq/archive/2009/09/14/generating-dynamic-methods-with-ex$p$pssion-trees-in-visual-studio-2010.aspx">this,但返回值实际上并不似乎没有任何地方规定。
我已经得到了所有的任务和放大器;东西下来,但我怎么指定从方法返回的对象使用前pression树木产生的?
编辑:这些都是V4 EX pression树和方法,我试图创造做这样的事情:
私有对象ReadStruct(读者BinaryReader在){
StructType OBJ =新StructType();
obj.Field1 = reader.ReadSomething();
obj.Field2 = reader.ReadSomething();
//...更多...
返回OBJ;
}
显然是返回
是<一个href="http://msdn.microsoft.com/en-us/library/system.linq.ex$p$pssions.gotoex$p$pssion.aspx"><$c$c>GotoEx$p$pssion$c$c>你可以创建<一个href="http://msdn.microsoft.com/en-us/library/system.linq.ex$p$pssions.ex$p$pssion.return.aspx"><$c$c>Ex$p$pssion.Return$c$c>工厂方法。你需要在年底创建标签跳转到它。事情是这样的:
//一个前pression重新presenting obj变量
ParameterEx pression objEx pression = ...;
LabelTarget returnTarget =前pression.Label(typeof运算(StructType));
GotoEx pression returnEx pression =前pression.Return(returnTarget,
objEx pression的typeof(StructType));
LabelEx pression returnLabel =前pression.Label(returnTarget,设置defaultValue);
BlockEx pression块=前pression.Block(
/ * ...变量,其他所有线路和...... * /,
returnEx pression,
returnLabel);
标签的目标和GOTO前pression的类型必须匹配。由于标签目标有一个类型,标签前pression必须有一个缺省值。
I'm trying to create a method using an expression tree that returns an object, but I can't figure out how to actually specify the object to return. I've tried reading this, but the return value doesn't actually seem to be specified anywhere.
I've got all the assignments & stuff down, but how do I specify the object to return from a method created using expression trees?
EDIT: these are v4 expression trees, and the method I'm trying to create does something like this:
private object ReadStruct(BinaryReader reader) {
StructType obj = new StructType();
obj.Field1 = reader.ReadSomething();
obj.Field2 = reader.ReadSomething();
//...more...
return obj;
}
Apparently a return
is a GotoExpression
that you can create with the Expression.Return
factory method. You need to create a label at the end to jump to it. Something like this:
// an expression representing the obj variable
ParameterExpression objExpression = ...;
LabelTarget returnTarget = Expression.Label(typeof(StructType));
GotoExpression returnExpression = Expression.Return(returnTarget,
objExpression, typeof(StructType));
LabelExpression returnLabel = Expression.Label(returnTarget, defaultValue);
BlockExpression block = Expression.Block(
/* ... variables, all the other lines and... */,
returnExpression,
returnLabel);
The types of the label target and the goto expression must match. Because the label target has a type, the label expression must have a default value.
这篇关于如何指定由一名前pression树方法返回的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!