Will all methods in a logical expressions be executed?

前端 未结 5 1952
我在风中等你
我在风中等你 2021-01-27 17:35

In C#, given the two methods

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

that are used in an if statement like this:

5条回答
  •  南方客
    南方客 (楼主)
    2021-01-27 18:16

    No, C# support logical short-circuiting so if Action1 returned true it would never evaluate Action2.

    This simple example shows how C# handles logical short-circuiting:

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

提交回复
热议问题