简体   繁体   English

如何使用Expression获取Func <ProductModel, int> 通过特定的字符串?

[英]How to use Expression to get Func<ProductModel, int> by a specific string?

I have following ProductModel and dictionary for SumGetters 我有以下ProductModel和SumGetters词典

public class ProductModel
{
    public int Id { get; internal set; }
    public int Column1 { get; internal set; }
    public int Column2 { get; internal set; }
    public int Column3 { get; internal set; }
}

private static readonly Dictionary<string, Func<ProductModel, int>> SumGetters = new Dictionary<string, Func<ProductModel, int>>
{
    { "Column1", model => model.Column1},
    { "Column2", model => model.Column2},
    { "Column3", model => model.Column3},
};

I try to get specific column from string. 我尝试从字符串获取特定的列。

Ex. 例如 if string is Column1, then get model=>model.Column1 如果字符串是Column1,则获取model=>model.Column1

How to use Expression Tree to achieve this function ? 如何使用表达式树实现此功能?

Func<ProductModel, int> sumGetter;
var isGettingSumGetter = SumGetters.TryGetValue(request.Column, out sumGetter);

Unclear what you are asking, BUT perhaps this is what you want: 不清楚您要问什么,但也许这就是您想要的:

private static readonly Dictionary<string, Func<ProductModel, int>> productModelGettersCache = new Dictionary<string, Func<ProductModel, int>>();

public static Func<ProductModel, int> GetGetter(string column)
{
    Func<ProductModel, int> getter;

    if (!productModelGettersCache.TryGetValue(column, out getter))
    {
        var par = Expression.Parameter(typeof(ProductModel));
        var exp = Expression.Lambda<Func<ProductModel, int>>(Expression.Property(par, column), par);
        getter = exp.Compile();
    }

    return getter;
}

Note that creating and compiling an expression tree is "slow", so I'm caching the created expressions. 请注意,创建和编译表达式树是“缓慢的”,因此我要缓存创建的表达式。 If you only want the expression tree before compilation, then you can find it in exp . 如果仅编译之前需要表达式树,则可以在exp找到它。

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

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