简体   繁体   中英

Return the generic class instance with anonymous type based on Newexpression

I have generic class "MSAccessQueryBuilder" with the following method

public I_QueryBuilder<T> Select(Expression<Func<T, object>> fieldNames)
    {
        NewExpression nEx = (NewExpression)fieldNames.Body;
        MsAccessQueryBuilder<"Anonymous Type Of Expression"> x = new MsAccessQueryBuilder<"Anonymous Type Of Expression">();

    }

within the method I need to create the instance of the "MSAccessQueryBuilder" with a generic type which anonymously created in lambda expression.

The method will be called like below

x.Select(s=> new {p1 = s.user_id,p2 = s.user_name})

Tried 8 hours of my own with no luck.

is this possible to get the anonymous type from NewExpression or LambdaExpression and create the instance of generic class of that anonymous type

Please help

Thank you

You can do like this.

var genericType = typeof(MsAccessQueryBuilder<>);
var specificType = genericType.MakeGenericType(typeof(nEx));
var x = Activator.CreateInstance(specificType);

have to change the method signature as Func delegate return type as generic instead of object solved the problem

public I_QueryBuilder<TResult> Select(Expression<Func<T, TResult>> fieldNames)
{

    return new MsAccessQueryBuilder<TResult>();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM