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

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

我有以下 SumGetters 的 ProductModel 和字典

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},
};

我尝试从字符串中获取特定列。

例如。如果字符串是 Column1,则得到 model=>model.Column1

如何使用Expression Tree来实现这个功能?

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

不清楚你在问什么,但也许这就是你想要的:

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;
}

请注意,创建和编译表达式树是 "slow",因此我正在缓存创建的表达式。如果你只想要 before 编译的表达式树,那么你可以在 exp.

中找到它