Created
February 19, 2014 14:17
-
-
Save dcastro/9093000 to your computer and use it in GitHub Desktop.
Build an Expression that instantiates an Anonymous Type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void CreateExpression() | |
{ | |
Type argType = typeof (MyClass); | |
string propertyName = "Name"; | |
ParameterExpression paramExpression = Expression.Parameter(argType, "item"); | |
//Create "item.Name" and "item.GetType()" expressions | |
var propertyAccessExpression = Expression.Property(paramExpression, propertyName); | |
var getTypeExpression = Expression.Call(paramExpression, "GetType", Type.EmptyTypes); | |
Type anonType = CreateAnonymousType<String, Type>("SelectedProp", "TypeOfProp"); | |
//"SelectProp = item.name" | |
MemberBinding assignment1 = Expression.Bind(anonType.GetField("SelectedProp"), propertyAccessExpression); | |
//"TypeOfProp = item.GetType()" | |
MemberBinding assignment2 = Expression.Bind(anonType.GetField("TypeOfProp"), getTypeExpression); | |
//"new AnonymousType()" | |
var creationExpression = Expression.New(anonType.GetConstructor(Type.EmptyTypes)); | |
//"new AnonymousType() { SelectProp = item.name, TypeOfProp = item.GetType() }" | |
var initialization = Expression.MemberInit(creationExpression, assignment1, assignment2); | |
//"item => new AnonymousType() { SelectProp = item.name, TypeOfProp = item.GetType() }" | |
Expression expression = Expression.Lambda(initialization, paramExpression); | |
} | |
public static Type CreateAnonymousType<TFieldA, TFieldB>(string fieldNameA, string fieldNameB) | |
{ | |
AssemblyName dynamicAssemblyName = new AssemblyName("TempAssembly"); | |
AssemblyBuilder dynamicAssembly = AssemblyBuilder.DefineDynamicAssembly(dynamicAssemblyName, AssemblyBuilderAccess.Run); | |
ModuleBuilder dynamicModule = dynamicAssembly.DefineDynamicModule("TempAssembly"); | |
TypeBuilder dynamicAnonymousType = dynamicModule.DefineType("AnonymousType", TypeAttributes.Public); | |
dynamicAnonymousType.DefineField(fieldNameA, typeof(TFieldA), FieldAttributes.Public); | |
dynamicAnonymousType.DefineField(fieldNameB, typeof(TFieldB), FieldAttributes.Public); | |
return dynamicAnonymousType.CreateType(); | |
} | |
public class MyClass | |
{ | |
public string Name { get; set; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment