简体   繁体   English

根据Newexpression返回具有匿名类型的泛型类实例

[英]Return the generic class instance with anonymous type based on Newexpression

I have generic class "MSAccessQueryBuilder" with the following method 我具有以下方法的通用类“ MSAccessQueryBuilder”

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. 在该方法中,我需要使用在lambda表达式中匿名创建的通用类型创建“ MSAccessQueryBuilder”的实例。

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. 我自己尝试了8个小时,没有运气。

is this possible to get the anonymous type from NewExpression or LambdaExpression and create the instance of generic class of that anonymous type 是否有可能从NewExpression或LambdaExpression获取匿名类型并创建该匿名类型的泛型类的实例

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 必须将方法签名更改为Func委托返回类型,将其更改为泛型而不是对象,从而解决了问题

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

    return new MsAccessQueryBuilder<TResult>();

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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