我有非常复杂的标准。让我们看看以下标准:
new List < ICriterion > {
Restrictions.Not(Restrictions.Eq("Name", user.Name)),
Restrictions.Or(
Restrictions.And(
Restrictions.And(
Restrictions.Eq("Status", user.Status))
...
))
...
};
但我需要根据一项设置有条件地添加一个限制。
if(Setting.SomeSettings)
{
new List < ICriterion > {
Restrictions.Not(Restrictions.Eq("Name", user.Name)),
Restrictions.Or(
Restrictions.And(
Restrictions.And(
**//new restriction**
Restrictions.Eq("Some", user.Some))
Restrictions.Eq("Status", user.Status))
...
))
...
};
}
else
{
new List < ICriterion > {
Restrictions.Not(Restrictions.Eq("Name", user.Name)),
Restrictions.Or(
Restrictions.And(
Restrictions.And(
Restrictions.Eq("Status", user.Status))
...
))
...
};
}
如何避免这种重复?
最佳答案
您可以将条件作为变量取出并使用它,例如,
ICriterion criterion;
if(Setting.SomeSettings)
{
criterion = Restrictions.And(
**//new restriction**
Restrictions.Eq("Some", user.Some))
Restrictions.Eq("Status", user.Status))
...
));
}
else
{
criterion = Restrictions.And(
Restrictions.And(
Restrictions.Eq("Status", user.Status))
...
));
}
new List < ICriterion > {
Restrictions.Not(Restrictions.Eq("Name", user.Name)),
Restrictions.Or(
Restrictions.And(
criterion
...
};
关于c# - 有条件地添加限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32471235/