如何使用设计模式C#转换具有多个条件的if-else

时间:2017-05-17 15:40:14

标签: design-patterns

我知道如果使用设计模式,如何在每个中使用单个条件转换if-else。 但现在我有点迷惑,因为在我的代码中有多个条件由&&和运营商如果。 现在如何重构这类案件。

代码如下:

    public ActionResult PaymentDetails(PaymentlistingDTOVM model, string SearchButton)
    {
        PaymentlistingDTOVM dto = new PaymentlistingDTOVM();

        if (model.PaymentSearch == null)
        {
            ModelState.AddModelError("Message", "Please select type to search ( Member No / Member Name).");
        }
        else if (model.PaymentSearch == "1" && model.Memberno == null)
        {
            ModelState.AddModelError("Message", "Please Enter Member No.");
        }
        else if (model.PaymentSearch == "2" && model.MemberName == null)
        {
            ModelState.AddModelError("Message", "Please Enter Member Name.");
        }
        else
        {
            if (!string.IsNullOrEmpty(model.SearchButton) || model.Page.HasValue)
            {
                if (model.Memberno != null)
                {
                    var Listpay = objIPaymentlisting.AllPaymentDetails(Convert.ToString(model.Memberno));

                    var results = Listpay.Where(p => (p.MemberID == model.Memberno));

                    var pageIndex = model.Page ?? 1;

                    model.SearchResults = results.ToPagedList(pageIndex, RecordsPerPage);
                }
                else if (model.MemberName != null)
                {
                    string[] Memno = model.MemberName.Split('|');

                    var Listpay = objIPaymentlisting.AllPaymentDetails(Convert.ToString(Memno[3]));

                    var results = Listpay.Where(p => (p.MemberID == Convert.ToInt32(Memno[3])));

                    var pageIndex = model.Page ?? 1;

                    model.SearchResults = results.ToPagedList(pageIndex, RecordsPerPage);
                }
            }
        }

        return View(model);
    }

1 个答案:

答案 0 :(得分:0)

您可以创建一个ICondition接口,接受PaymentlistingDTOVM实例,如下所示

public interface ICondition<T>
{
   bool IsSatisfied(T obj);
}

然后您可以为每个案例创建一个实现。当然,由于实现将非常小,您可以创建一个通用的实现,如:

public class FuncBasedCondition<T> : ICondition<T>
{
   private readonly Func<T, bool> predicate;

   public FuncBasedCondition(Func<T, bool> predicate)
   {
       this.predicate = predicate;
   }

   //For C# 6, expression-bodied members can be used like this
   //public bool IsSatisfied(T obj) => predicate(obj);
   public bool IsSatisfied(T obj)
   {
       return predicate(obj);
   }
}

例如,要为第一个条件创建实例,请按以下步骤创建条件类的实例:

new FuncBasedCondition<PaymentlistingDTOVM>(model => model.PaymentSearch == null);

然后,调整您的控制器(或您所显示的代码所在的位置),以接受对您需要处理的不同条件的不同引用。