Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use an expression tree to define a method body for dynamic types?

If I'm creating a dynamic type like so:

TypeBuilder dynaType = dynaModule.DefineType(typeof(T).Name + "_ORMProxy");

dynaType.AddInterfaceImplementation(typeof(IServiceTable));

// (1) Implement: (String) IServiceTable.TableName { get; }
FieldBuilder tableNameField = dynaType.DefineField("tableName", typeof(String), FieldAttributes.Private);
MethodBuilder tableNamePublicGetAccessor = dynaType.DefineMethod("get_tableName", MethodAttributes.Public);
tableNamePublicGetAccessor...

Is it possible to set the GetAccessor method to an expression tree. They're much easier to work with than straight IL.

like image 992
sircodesalot Avatar asked Jun 11 '13 14:06

sircodesalot


People also ask

What are expression trees used for?

Expression Trees represent code as a structure that you can examine, modify, or execute. These tools give you the power to manipulate code during run time. You can write code that examines running algorithms, or injects new capabilities.

What is expression trees and how they used in LINQ?

Expression Trees was first introduced in C# 3.0 (Visual Studio 2008), where they were mainly used by LINQ providers. Expression trees represent code in a tree-like format, where each node is an expression (for example, a method call or a binary operation such as x < y).

What is an expression tree give an example?

Each node in an expression tree is an expression. For example, an expression tree can be used to represent mathematical formula x < y where x, < and y will be represented as an expression and arranged in the tree like structure. Expression tree is an in-memory representation of a lambda expression.


2 Answers

Yes and no. The LambdaExpression.CompileToMethod() method will let you compile an expression tree to a MethodBuilder only if the method is static. It cannot be used to implement instance methods, which I believe is what you want in your example.

like image 176
Mike Strobel Avatar answered Sep 19 '22 13:09

Mike Strobel


That's exactly what the LambdaExpression.CompileToMethod() method is for.

like image 39
svick Avatar answered Sep 18 '22 13:09

svick