【问题标题】:Will all methods in a logical expressions be executed?是否会执行逻辑表达式中的所有方法?
【发布时间】:2009-04-23 13:57:12
【问题描述】:

在C#中,给定两种方法

 bool Action1(object Data);
bool Action2(object Data);

if 语句中使用,如下所示:

if ( Action1(Data) || (Action2(Data) )
{
    PerformOtherAction();
}

如果 Action1() 返回 true,是否仍会调用 Action2(),或者编译器优化会阻止这种情况,因为已知表达式将计算为 true

【问题讨论】:

    标签: c# optimization


    【解决方案1】:

    不,C# 支持逻辑短路,因此如果 Action1 返回 true,它将永远不会评估 Action2

    这个简单的例子展示了 C# 如何处理逻辑短路:

    using System;
    
    class Program
    {
        static void Main()
        {
            if (True() || False()) { }  // outputs just "true"
            if (False() || True()) { }  // outputs "false" and "true"
            if (False() && True()) { }  // outputs just "false"
            if (True() && False()) { }  // outputs "true" and "false"
        }
    
        static bool True()
        {
            Console.WriteLine("true");
            return true;
        }
    
        static bool False()
        {
            Console.WriteLine("false");
            return false;
        }
    }
    

    【讨论】:

      【解决方案2】:

      只有在 Action1() 返回 false 时才会调用 Action2()

      这在概念上类似于

      if (Action1(Data))
      {
          PerformOtherAction();
      } 
      else if (Action2(Data))
      {
          PerformOtherAction();
      } 
      

      【讨论】:

        【解决方案3】:

        您可以使用单个 |或 & 让这两种方法都执行。这是 Brainbench C# 考试希望您知道的技巧之一。在现实世界中可能没有任何用处,但仍然很高兴知道。此外,它还可以让您以创造性和狡猾的方式迷惑您的同事。

        【讨论】:

        • 谢谢!能否提供一个文档链接来进一步解释这一点?
        【解决方案4】:

        由于短路评估规则,如果 Action1 返回 true,则不会调用 Action2。请注意,这是运行时优化,而不是编译时优化。

        【讨论】:

          【解决方案5】:

          如果 Action1() 返回 true,则不会评估 Action2()。 C#(如 C 和 C++)使用短路评估。 MSDN Link 这里验证一下。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2012-02-28
            • 2013-08-25
            • 1970-01-01
            • 2023-01-19
            • 1970-01-01
            • 1970-01-01
            • 2012-11-13
            相关资源
            最近更新 更多