Skip to content

Expression 'GetValue' method is not work in parameterized anonymous object NewExpression case #1166

Open
@leafkevin

Description

@leafkevin

Bug Description

Anonymous object, will report an error at the time of construction, anonymous objects are parameterized.
The anonymous object is

new { TotalAmount = 25, Products = new List<int> { 1, 2 } }

where code excuted here

public static object GetValue(this NewExpression expression)
{
    if (expression.Arguments?.Count != 0)
    {
        return Activator.CreateInstance(expression.Constructor.DeclaringType,
            expression.Arguments?.Select(arg => arg.GetValue()));
    }
    else
    {
        return Activator.CreateInstance(expression.Constructor.DeclaringType);
    }
}

exception has happened.

Exception Message:

System.MissingMethodException:“Constructor on type '<>f__AnonymousType29`2[[System.Int32, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.Collections.Generic.List`1[[System.Int32, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]' not found.

I changed to this, it's work.

public static object GetValue(this NewExpression expression)
{
    if (expression.Arguments.Count > 0)
        return Activator.CreateInstance(expression.Type, expression.Arguments.Select(arg => arg.Evaluate()).ToArray());
    else return Activator.CreateInstance(expression.Type);
}

Metadata

Metadata

Assignees

Labels

bugSomething isn't workingtodoThings to be done in the future

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions