C# 如何使用表达式通过特定字符串获取Func?

C# 如何使用表达式通过特定字符串获取Func?,c#,lambda,expression,func,C#,Lambda,Expression,Func,我有以下产品模型和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 rea

我有以下产品模型和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},
};

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

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

请注意,创建和编译表达式树的速度很慢,因此我正在缓存创建的表达式。如果在编译之前只需要表达式树,那么可以在exp.

中找到它。因此,给定Column1字符串和ProductModel类型,您需要model=>model.Column1表达式吗?@xanatos是的,您得到了它。
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;
}