【问题标题】:Proper (or different) method of queuing dependent methods排队依赖方法的正确(或不同)方法
【发布时间】:2014-07-26 07:02:58
【问题描述】:

这是关于正确代码样式的问题。假设我有几种方法,如果前一种方法为假,则无法执行。

我怎样才能正确地编写它(或者如果没有“正确”的方法,那么至少是一个不同的方法),这样我就不必在下面构建这样的树,因为这样的树可能会越来越大。

class Client
{
    static void Main()
    {
        if(Connect())
        {
            if(Fetch())
            {
                if(Parse())
                {
                    Print();
                }
            }
        }
    }

    bool Connect() { ... }

    bool Fetch() { ... }

    bool Parse() { ... }

    void Print() { ... }
}

【问题讨论】:

标签: c# styling code-formatting


【解决方案1】:

您可以将它包装在一个接受一堆委托的方法中:

public bool AllTrue(params Func<bool>[] methods) {
    foreach (var method in methods) {
        if (!method())
            return false;
    }
    return true;
}

..然后这样称呼它:

if (AllTrue(Connect, Fetch, Parse)) {
    Print();
}

这当然比链接逻辑 AND 更有趣。

【讨论】:

    【解决方案2】:

    您可以在单个 if 条件中检查所有条件,而不是编写多个 if 条件

    If (Connect() && Fetch() && Parse())
    

    这里,如果条件首先检查 Connect() 方法的值,如果返回 false,则不会检查其他条件。

    【讨论】:

      【解决方案3】:

      在这种情况下你可以使用

      static void Main()
      {
          if(Connect() && Fetch() && Parse())
          {
              Print();
          }
      }
      

      或者

      static void Main()
      {
          if(!Connect())
              return;
          if(!Fetch())
              return;
          if(!Parse())
              return;
          Print();
      }
      

      【讨论】:

        猜你喜欢
        • 2016-09-15
        • 2011-08-15
        • 1970-01-01
        • 2023-04-08
        • 2013-07-02
        • 2023-04-04
        • 1970-01-01
        • 2011-12-03
        • 1970-01-01
        相关资源
        最近更新 更多