懒惰的评价不是那么懒惰吗? [英] Lazy Evaluation not so Lazy?

查看:77
本文介绍了懒惰的评价不是那么懒惰吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直听说C#使用惰性评估.因此,对于某些类似的代码,if (true || DoExpensiveOperation()将返回true而不执行DoExpensiveOperation().

I've always heard C# uses lazy evaluation. So for certain code like, if (true || DoExpensiveOperation() will return true without executing DoExpensiveOperation().

在一次面试中,我看到了以下问题,

On an interview test I saw the following questions,

static bool WriteIfTrue(bool argument)
{
    if (argument)
    {
        Console.WriteLine("argument is true!");
    }

    return argument;
}

static void Main()
{
    // 1              0                       0                 1
    WriteIfTrue((WriteIfTrue(false) & WriteIfTrue(true)) || WriteIfTrue(true));

    // 1               1                     0                      1
    WriteIfTrue((WriteIfTrue(true) || WriteIfTrue(false)) & WriteIfTrue(true));

    //  0                 0                  0                    0
    WriteIfTrue((WriteIfTrue(false) & WriteIfTrue(true)) & WriteIfTrue(false));

    // 1                1                      0                   1
    WriteIfTrue((WriteIfTrue(true) || WriteIfTrue(false)) & WriteIfTrue(true));
}

它将打印多少次参数为真!"到屏幕上?

How many times would it print "argument is true!" to the screen?

我会说7是正确的答案.现在,如果我坚持使用编译器并运行它,它将打印10次!懒惰的评估哪里出错了?

I would say 7 is the correct answer. Now if I stick into the compiler and run it, it prints it 10 times! Where did lazy evaluation all go wrong?

推荐答案

我一直听说C#使用惰性评估.

I've always heard C# uses lazy evaluation.

对于我来说,我的评论太含糊了.如果您说C#中的||&&运算符正在短路,则仅在无法仅从第一个操作数 then 不能确定整体结果的情况下,才评估第二个操作数我会同意的.延迟评估是一个范围更广的概念-例如,LINQ查询使用延迟(或延迟)评估,直到使用结果后才真正获取任何数据.

That's far too vague a comment for me to agree with. If you'd said that the || and && operators in C# are short-circuiting, only evaluating the second operand if the overall result couldn't be determined just from the first operand, then I'd agree with it. Lazy evaluation is a more wide-ranging concept - for example, LINQ queries use lazy (or deferred) evaluation, not actually fetching any data until the result is used.

您正在使用 &运算符,而不是短路:

You're using the & operator, which isn't short-circuiting:

&运算符会评估两个运算符,而与第一个运算符的值无关.

The & operator evaluates both operators regardless of the first one's value.

&&运算符 短路:

操作x && y对应于操作x & y,不同之处在于,如果x为false,则不评估y,因为无论y的值是多少,AND操作的结果均为false. .

The operation x && y corresponds to the operation x & y except that if x is false, y is not evaluated, because the result of the AND operation is false no matter what the value of y is.

在代码中的任何地方用&&替换&,您将看到参数为真!"打印了8次(不是7次-请再计算一次您的评论).

Replace & with && everywhere in your code, and you'll see "argument is true!" printed 8 times (not 7 - count your comments again).

这篇关于懒惰的评价不是那么懒惰吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆