要获取类型的属性,您可以依赖反射。见How to get the list of properties of a class?
然后您可以使用表达式树来构建动态谓词。见How do I dynamically create an Expression<Func<MyClass, bool>> predicate?
但我建议采用更简单(但涉及更多打字)的方法。
拥有一个应该由您的所有Ts 实现的接口。比如:
public interface Searchable
{
IEnumerable<ParamInfo> Params { get; }
Func<string, decimal, decimal, bool> Predicate { get; }
}
还有一个ParamInfo 类:
public class ParamInfo
{
public string LabelText { get; private set; }
public Type EditControl { get; private set; }
public Type DataType { get; private set; }
public object DefaultValue { get; private set; }
public bool Required { get; private set; }
//etc. basically a good info class the decides how to draw gui
}
然后您的搜索表单可以是
public partial class SearchForm<T> where T : Searchable
{
....
}
还有波科:
public class Order : Searchable
{
public string OrderNumber {get; set;}
public decimal OrderWeight {get; set;}
public IEnumerable<ParamInfo> Params
{
get
{
return new List<ParamInfo>
{
new ParamInfo(typeof(TextBox), typeof(string), "Enter value", true),
new ParamInfo(typeof(TextBox), typeof(decimal), 0, true),
new ParamInfo(typeof(TextBox), typeof(decimal), 0, true)
}
}
}
public Func<string, decimal, decimal, bool> Predicate
{
get
{
return (s, d1, d2) => OrderNumber.Contains(s)
&& OrderWeight >= d1
&& OrderWeight <= d2; //and so on, u get the idea.
}
}
这提供了更多的灵活性。您可以直接将谓词附加到每个Ts 中的ParamInfo 类,而不是动态地 构建谓词。这是我们在您的项目中使用的东西。