这是有点误导你有一个类和属性CustomerFilter
代表非常不同的事情。据我了解,这个类将更好地被命名为Customer
:
public class Customer
{
public int Id { get; set; }
public int Name { get; set; }
}
public class Search
{
private Expression<Func<Customer, bool>> customerfilter;
public Expression<Func<Customer, bool>> CustomerFilter
{
set { customerfilter = value; }
}
}
var search = new Search();
search.CustomerFilter = (x => x.Id == 1);
然后更明显的是,有一个在您Search
类没有财产customerFilter.Id
。你只有一个表达式,可以采取任何(!)Customer
并将其转换为bool
。它通过将Customer.Id
与给定值进行比较来实现,但Search
不知道这一点。
如果你需要得到比较ID在Search
,我建议你改变CustomerFilter
属性的类型具有公共ComparisonId
财产,并基于该ID的过滤表达式类:
class CustomerIdFilter // note: this will not replace your existing CustomerFilter which I have renamed to Customer
{
public CustomerIdFilter(int id){ ComparisonId = id; }
public int ComparisonId{ get; private set}
// To filter use this
public bool IsValid(Customer c){ return c.Id == ComparisonId; }
// or maybe something similar to this, if necessary
public Expression<Func<Customer, bool>>FilterExpression
{
get
{
return (x=>x.Id == ComparisonId);
}
}
}
你的代码会改成s.th.这样便:
public class Search
{
private CustomerIdFilter customerfilter;
public CustomerIdFilter CustomerFilter
{
set { customerfilter = value; }
}
}
var search = new Search();
search.CustomerFilter = new CustomerIdFilter(1);
来源
2017-02-22 08:35:33
wkl
你从'CustomerFilter的新实例所获得的价值'。我需要从表达式本身获得价值。 –
表达式没有任何实例,您可以构建一个获取值的新表达式,但您需要一个实例来应用 –