有条件地添加限制

Add restriction conditionally

我的标准非常复杂。让我们看看以下标准:

         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   
                        ...
                 };