【发布时间】:2020-03-31 19:42:21
【问题描述】:
我有一种情况,我想根据强加于特定类型的谓词集合过滤对象:
这可以通过预编译的ExpressionTrees 来完成吗?
class A
{
public int Value {get;set;}
}
class B
{
public string Name {get;set;}
public bool IsMajor{get;set;}
}
Dictionary<Type,IEnumerable<Predicate<[object casted to type]>> typePredicateMap=new Dictionary<Type,Predicate<[object casted to type]>>{
{typeof(A),new List<Predicate<[object casted to A]> { x=>x.Value >100,x=>x.Value<200 }},
{typeof(B),new List<Predicate<[object casted to B]> { x=>x.Name!="johhnny",x=>x.IsMajor==true }}
}
我在上面说过object casted to Type,因为我希望我的谓词基于那个特定类型..
public static bool MeetsCriteria(object data)
{
Type type=typeof(data);
IEnumerable<Predicate<object>predicates=typePredicateMap[type];
bool isValid=true;
foreach(var predicate in predicates)
{
isValid&=predicate(data); //
}
return isValid;
}
【问题讨论】:
标签: c# expression-trees predicate