2

我的 Windows 应用程序项目中有一个ListForm<T>表单。我也以那种形式定义了predicate字段Func<Order,bool>

private Func<T,bool> predicate;

ListForm可以创建不同的类型,例如OrderDTO, CustomerDTO, DocumentDTO,...

public class OrderDTO
{
   public string Number {get; set;}
   public string CustomerName {get; set;}
   public int Weight {get; set;}
}

public class CustomerDTO
{
   public int CustomerId {get; set;}
   public string CustomerName {get; set;}
}

有什么方法可以让我predicate在运行时动态地构建所有<T>类型的属性?(假设总是字符串必须与"X"整数进行比较0)例如,如果ListForm使用OrderDTO类型创建predicate应该是:

t=>t.Number == "X" && t.CustomerName == "X" && t.Weight == 0;

如果它使用CustomerDTO类型创建,谓词应该是

t=> t.CustomerId == 0 && t.CustomerName == "X";

我想用它来创建动态搜索表单。

事实上,我有一个过滤器选择窗口,用户可以将他的过滤条件定义为数据ListForm,并且这个过滤器窗口动态创建,如我在基于 ISearchable 类型创建通用搜索表单中所述

4

1 回答 1

0

如下构建您的谓词:

private void BuildPredicate()
    {
        predicate = (obj) =>
        {
            var t = typeof(T);
            var strProps = t.GetProperties().Count(p => p.PropertyType == typeof(string) && p.GetValue(obj, null) != "X");
            var intProps = t.GetProperties().Count(p => p.PropertyType == typeof(int) && (int)p.GetValue(obj, null) != 0);
            if (strProps == 0 && intProps == 0)
            {
                return true;
            }
            return false;
        };
    }
于 2013-06-17T10:28:26.773 回答