将C#表达式树编译为方法时,可以访问“ this”吗?

时间:2019-05-08 20:40:08

标签: c# code-generation expression-trees

我试图动态生成一个实现给定接口的类。因此,我需要实现一些方法。我想避免直接发出IL指令,因此我尝试使用表达式树和CompileToMethod。不幸的是,其中一些方法需要访问所生成类的字段(就像我将this.field写入要实现的方法中一样)。是否可以使用表达式树访问“ this”? (通过“ this”,我的意思是将调用该方法的对象。)

如果是,那么表达式树的这种方法是什么样的?

int SomeMethod() {
    return this.field.SomeOtherMethod();
}

1 个答案:

答案 0 :(得分:2)

May 08 18:36:07 ip-10-0-1-87 postgresql@11-main[3617]: 2019-05-08 18:36:06.776 UTC [3623] PANIC: could not write to file "pg_wal/xlogtemp.3623": No Expression.Constant是您的朋友;例子:

ParameterExpression

或:

var obj = Expression.Constant(this);
var field = Expression.PropertyOrField(obj, "field");
var call = Expression.Call(field, field.Type.GetMethod("SomeOtherMethod"));
var lambda = Expression.Lambda<Func<int>>(call);

(在后一种情况下,您将var obj = Expression.Parameter(typeof(SomeType)); var field = Expression.PropertyOrField(obj, "field"); var call = Expression.Call(field, field.Type.GetMethod("SomeOtherMethod")); var lambda = Expression.Lambda<Func<SomeType, int>>(call, obj); 作为参数传递,但这意味着您可以存储lambda并将其重新用于不同的目标实例对象)

如果您的姓名固定,这里的另一个选项可能是this

dynamic
相关问题