How to use Expression to build an Anonymous Type?

前端 未结 3 640
一生所求
一生所求 2020-12-03 03:00

In C# 3.0 you can use Expression to create a class with the following syntax:

var exp = Expression.New(typeof(MyClass));
var lambda = LambdaExpression.Lambda         


        
3条回答
  •  时光说笑
    2020-12-03 03:24

    You're close, but you have to be aware that anonymous types don't have default constructors. The following code prints { Name = def, Num = 456 }:

    Type anonType = new { Name = "abc", Num = 123 }.GetType();
    var exp = Expression.New(
                anonType.GetConstructor(new[] { typeof(string), typeof(int) }),
                Expression.Constant("def"),
                Expression.Constant(456));
    var lambda = LambdaExpression.Lambda(exp);
    object myObj = lambda.Compile().DynamicInvoke();
    Console.WriteLine(myObj);
    

    If you don't have to create many instances of this type, Activator.CreateInstance will do just as well (it's faster for a few instances, but slower for many). This code prints { Name = ghi, Num = 789 }:

    Type anonType = new { Name = "abc", Num = 123 }.GetType();
    object myObj = Activator.CreateInstance(anonType, "ghi", 789);
    Console.WriteLine(myObj);
    

提交回复
热议问题