我的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"
和{{1}的整数进行比较例如,如果使用0
类型ListForm
创建的OrderDTO
应为:
predicate
如果使用t=>t.Number == "X" && t.CustomerName == "X" && t.Weight == 0;
类型创建,则谓词应为
CustomerDTO
我想用它来创建动态搜索表单。
实际上我有一个过滤器选择窗口,用户可以在t=> t.CustomerId == 0 && t.CustomerName == "X";
中为数据定义他的过滤条件,这个过滤器窗口动态创建,如Creating a generic search form based on ISearchable types
答案 0 :(得分: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;
};
}