How to use Expression to build an Anonymous Type?

前端 未结 3 633
一生所求
一生所求 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:34

    Since an anonymous type doesn't have a default empty constructor, you cannot use the Expression.New(Type) overload ... you have to provide the ConstructorInfo and parameters to the Expression.New method. To do that, you have to be able to get the Type ... so you need to make a "stub" instance of the anonymous type, and use that to get the Type, and the ConstructorInfo, and then pass the parameters to the Expression.New method.

    Like this:

    var exp = Expression.New(new { Name = "", Num = 0 }.GetType().GetConstructors()[0], 
                             Expression.Constant("abc", typeof(string)), 
                             Expression.Constant(123, typeof(int)));
    var lambda = LambdaExpression.Lambda(exp);
    object myObj = lambda.Compile().DynamicInvoke();
    

提交回复
热议问题