从对象创建动态 Func<T, TResult>

4

我有一个条件对象,如果它的值不为空,我想将每个属性转换为函数。

public class TestClassCriteria
{
    public bool? ColumnA { get; set; }
    public bool? ColumnB { get; set; }
}

到目前为止,这就是我所做的但我很确定我没有正确定义lambda表达式。下面是我想要实现的内容:funcs.Add(x => x.ColumnA == criteria.ColumnA)

var properties = criteria.GetType().GetProperties();
var funcs = new List<Func<dynamic, bool>>();

foreach (var property in properties)
{
    var propertyName = property.Name;

    funcs.Add(x => x.GetType().GetProperty(propertyName).Name == criteria.GetType().GetProperty(propertyName).Name);
}

它没有崩溃或引起任何错误,只是无法正常工作。

如果您能提供任何帮助,将不胜感激。


首先,lambda表达式应该有花括号,所以你需要将 x => x.ColumnA == criteria.ColumnA 改为 (x) => {x.ColumnA == criteria.ColumnA;}。我还认为你想要它返回一个bool值,这种情况下它会变成 (x) => {return x.ColumnA == criteria.ColumnA;}。不过我不确定你具体想要做什么。 - Pharap
1
“lambdas should have curly braces” 不完全正确…… {} 也会防止将 lambda 用作表达式(根据我的理解,这大概是 OP 尝试做的),但允许创建具有多个语句的委托。 - Alexei Levenkov
2个回答

5
你是否想要类似这样的东西?
    static List<Func<TEntity, TCriteria, bool>> GetCriteriaFunctions<TEntity, TCriteria>()
    {
        var criteriaFunctions = new List<Func<TEntity, TCriteria, bool>>();

        // searching for nullable properties of criteria
        var criteriaProperties = typeof(TCriteria)
            .GetProperties()
            .Where(p => p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>));

        foreach (var property in criteriaProperties)
        {
            // this is entity parameter
            var entityParameterExpression = Expression.Parameter(typeof(TEntity));
            // this is criteria parameter
            var criteriaParameterExpression = Expression.Parameter(typeof(TCriteria));
            // this is criteria property access: "criteria.SomeProperty"
            var criteriaPropertyExpression = Expression.Property(criteriaParameterExpression, property);
            // this is testing for equality between criteria property and entity property;
            // note, that criteria property should be converted first;
            // also, this code makes assumption, that entity and criteria properties have the same names
            var testingForEqualityExpression = Expression.Equal(
                Expression.Convert(criteriaPropertyExpression, property.PropertyType.GetGenericArguments()[0]), 
                Expression.Property(entityParameterExpression, property.Name));

            // criteria.SomeProperty == null ? true : ((EntityPropertyType)criteria.SomeProperty == entity.SomeProperty)
            var body = Expression.Condition(
                Expression.Equal(criteriaPropertyExpression, Expression.Constant(null)), 
                Expression.Constant(true),
                testingForEqualityExpression);

            // let's compile lambda to method
            var criteriaFunction = Expression.Lambda<Func<TEntity, TCriteria, bool>>(body, entityParameterExpression, criteriaParameterExpression).Compile();

            criteriaFunctions.Add(criteriaFunction);
        }

        return criteriaFunctions;
    }

示例实体和示例条件:

class CustomerCriteria
{
    public int? Age { get; set; }
    public bool? IsNew { get; set; }
}

class Customer
{
    public string Name { get; set; }
    public int Age { get; set; }
    public bool IsNew { get; set; }
}

使用方法:

        var criteriaFunctions = GetCriteriaFunctions<Customer, CustomerCriteria>();
        var customer1 = new Customer { Name = "John", Age = 35, IsNew = false };
        var customer2 = new Customer { Name = "Mary", Age = 27, IsNew = true };
        var criteria1 = new CustomerCriteria { Age = 35 };
        var criteria2 = new CustomerCriteria { IsNew = true };

        Console.WriteLine("Is match: {0}", criteriaFunctions.All(f => f(customer1, criteria1)));
        Console.WriteLine("Is match: {0}", criteriaFunctions.All(f => f(customer2, criteria1)));
        Console.WriteLine("Is match: {0}", criteriaFunctions.All(f => f(customer1, criteria2)));
        Console.WriteLine("Is match: {0}", criteriaFunctions.All(f => f(customer2, criteria2)));

与使用动态代码不同,此代码使用强类型成员访问,因此您可以缓存每个“实体-条件”对的条件列表,并更快地测试匹配实例。


这个方法很有效,非常感谢。如果有人感兴趣的话,我按照他上面概述的方式实现了它。 - bkorzynski

1
您当前的表达式正在比较属性名称,但我认为您想要比较属性值:
var funcs = new List<Func<dynamic, bool>>();

foreach (var property in criteria.GetType().GetProperties())
{
    funcs.Add(x => x.GetType().GetProperty(property.Name).GetValue(x, null) == property.GetValue(criteria, null));
}

然而,您确定需要这样做吗?可能有更好的方法重构您的代码,以便您不需要使用反射来比较两个不相关对象上恰好具有相同名称的属性。


当我尝试这个时,我得到了一个错误 Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 运算符“==”不能应用于类型为“bool”和“object”的操作数。即使我进行了强制转换,它仍然无法正常工作。我认为下面的响应更接近我们所需要的。我会尝试一下并让你知道结果。 - bkorzynski

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接